# Console / shell tips & tricks

## carambola5

Yes, we all know how to alias stuff in /etc/profile or ~/.bashrc or whatever.  Some favorites of (seemingly) everyone are:

```
alias ls='ls --color'

alias sl='ls --color'
```

The list is brief, but that's where the rest of this thread comes into play:  What are some quick little console (if you want X-tricks, start another thread, please!) tricks that you employ?

Here are some of mine:

script called "remote" that can optionally take in an argument.  If there is an argument, it's a nickname for an ssh server.  If there is no argument, list the predefined ssh servers and pick from the menu.  This is useful if you like to forward ports often.

alias rm='rm -f' I'm feeling lucky  :Very Happy: 

EDIT:  Title was "quick console tricks" --pjp

----------

## nitro322

```
alias 2000='su -c "lilo -R 2000" && reboot'
```

reboot to Windows 2000 without the LILO prompt

2000 = the lilo name for my Windows 2000 entry

```
alias c='clear'

alias md='mkdir'

alias rd='rmdir'

alias dir='ls -Alh --color | more'
```

I'm lazy   :Smile: 

```
alias gpm='sudo /etc/init.d/gpm start'

alias halt='sudo /sbin/halt'

alias reboot='sudo /sbin/reboot'

alias renet='sudo /etc/init.d/net.eth0 restart'
```

more various shortcuts to save me time

```
alias kernel_comp='cd /usr/src/linux/ && cp .config .. && make clean && make mrproper && cp ../.config . && make menuconfig && make dep && make bzImage modules modules_install && cp System.map /boot/System.map-020916 && cp arch/i386/boot/bzImage /boot/bzImage-020916 && lilo && echo "finished"'
```

who's your daddy?   :Wink: 

I guess that's just about it.  I also run my console at 1024x768 resolution with 8-bit color, which gives me a LOT more room to work, in addition to being purtier.  If you haven't noticed, the left and right windows keys on your keyboard will change you to the virtual terminal to the left and right of your current one.  Nice.

----------

## dioxmat

 *nitro322 wrote:*   

> 
> 
> ```
> alias kernel_comp='cd /usr/src/linux/ && cp .config .. && make clean && make mrproper && cp ../.config . && make menuconfig && make dep && make bzImage modules modules_install && cp System.map /boot/System.map-020916 && cp arch/i386/boot/bzImage /boot/bzImage-020916 && lilo && echo "finished"'
> ```
> ...

 

nah, you forgot to evaluate the time it took :)

----------

## fmalabre

 *nitro322 wrote:*   

> reboot to Windows 2000 without the LILO prompt

 

Can we do the same thing with Grub?

----------

## pjp

I could've sworn I'd seen it done somewhere, but I'm not finding it.

----------

## rojaro

there is no such function in grub and there are just two "halfway methods" which work ... well just half the way ...

1. is to use multiple menu.lst files and a shellscript which exchanges the config files (which is pretty easy to implement)

2. use a shellscript which changes the "default"-parameter in the menu.lst file using sed (imho the nicer way). this shellscript should reset the menu.lst to the real default when called without parameters and you could add it to /etc/conf.d/localstart to change the parameter back to default automatically on next linuxboot ... 

sure you'll see why this is only a halfway solution ...

[edit: ... just filed a feature request at their bugzilla]

----------

## NickDaFish

 *Quote:*   

> alias ls='ls --color' 
> 
> 

 

 :Very Happy:  YES! Many thanks! I've been trying to work out how to make bash do that for AGES! It's default in RedHat and I've been missing it ever since I went over to Gentoo... Too many other things to figure out first  :Wink:  so I never go to it.

BTW Does anyone know how to get my Home key to work with in a PuTTY SSH session? I think it's something to do with inputrc..... I have Ctrl-a to get me by for now but I'd it would be nice to get my keyboard to work as advertised   :Confused: 

----------

## carambola5

(Using lynx while bootstrapping, so I don't know how this'll turn out.)

I forgot one very key alias in my first post:

```
alias pico='nano -w'
```

And life just became much easier. : )

----------

## phong

I have lots of aliases to save myself some typing, many are either from DOS or even from .bat files I made in the DOS days for the same purpose:

```
alias vi='vim -o -X'

alias vim='vim -o -X'

alias vimdiff='vimdiff -X'

alias dir='ls --color -Flh'

alias dirh='ls --color -Flah'

alias di='dir' # my most common command line typo is hitting enter before 'r' in dir

alias r=''

alias cls='clear' # actually, I usually just hit ctrl-l

alias x='exit'

alias rd='rmdir'

alias md='mkdir'

alias h='history'

alias mo='more'

alias le='less'

alias ks='kfmclient exec' # like the windows "start" command

alias nc='mc'

alias cd/='cd /'

alias cd..='cd ..'

alias cd...='cd ../..'

alias cd....='cd ../../..'

alias ..='cd ..'

alias ...='cd ../..'

alias ....='cd ../../..'
```

----------

## tactless

Not really a "trick", but here's something I put in my bashrc:

```
fortune
```

Great way to start the day  :Smile: [/code]

----------

## wbsoft

```

nd() { test -d "$1" || mkdir "$1" && cd "$1" ; }

alias o="less -iMS"

nX()

{

  for i in `seq 0 9`

  do

    if [ ! -e "/tmp/.X${i}-lock" ] ; then

      XFree86 ":$i" -query localhost &

      break

    fi

  done

}

```

the last one, nX, starts a new X login on a new display. (You should add localhost to /etc/X11/xdm/Xaccess)

----------

## squanto

I read somewhere how to customize bash, with like the full current directory path, the time, and a whole bunch of other things.  Any one want to give me a quick heads up to an article on how to do this?

I think it fits in with neat things to do with customizing your shell.

thanks!

----------

## carlivar

 *squanto wrote:*   

> I read somewhere how to customize bash, with like the full current directory path, the time, and a whole bunch of other things.  Any one want to give me a quick heads up to an article on how to do this?
> 
> 

 

Go here for a very nice thread with many bash prompt examples.

Carl

----------

## squanto

 *carlivar wrote:*   

>  *squanto wrote:*   I read somewhere how to customize bash, with like the full current directory path, the time, and a whole bunch of other things.  Any one want to give me a quick heads up to an article on how to do this?
> 
>  
> 
> Go here for a very nice thread with many bash prompt examples.
> ...

 

Hey, thanks!

I read an article about customizing bash in CPU mag, but misplaced the article.

I don't like how gnome's term doesn't list anything.

as for my aliases: alias sshserver="ssh my.server.name.edu"

so I can ssh into my game server  :Wink:  (modified obviously)

Andrew

----------

## NiklasH

 *wbsoft wrote:*   

> 
> 
> ```
> 
> nd() { test -d "$1" || mkdir "$1" && cd "$1" ; }
> ...

 

I can't get this to work...

The nX function starts a new X window, but I get no login prompt (gdm, in my case).

Am I doing something wrong? I tried to add just 'localhost' in Xaccess. Should I add something more? I also tried to add CHOOSER localhost, but that didn't work either.

Maybe I'm just stupid...    :Confused:  But I would really like this to work, so any help is very appreciated!

----------

## klieber

I find it remarkable how many people don't use the history command.  That, combined with the '!n' to re-issue a frequently-used command saves me tons and tons of time.

man history if you have no idea what I'm talking about.

--kurt

----------

## carambola5

I definitely do not claim to be a proficient bash programmer.  But hey, it works.  I call it 'remote':

```
#!/bin/bash

SERVERS="CAE CS Quit"

ENGR="cae.my_u.edu"

COMPSCI="cs.my_u.edu"

if [ -z "$1" ]; then

   select serv in $SERVERS; do

      if [ "$serv" = "CAE" ]; then

         ssh $ENGR

         exit

      elif [ "$serv" = "CS" ]; then

         ssh $COMPSCI

         exit

      elif [ "$serv" = "Quit" ]; then

         exit

      else

         echo bad option

         echo 

      fi

   done

else

   if [ "$1" = "cae" ]; then

      ssh $ENGR

   elif [ "$1" = "cs" ]; then

      ssh $COMPSCI

   else

      echo Bad argument.  Servers are cs or cae

      echo eg:  remote cae

   fi

fi

```

----------

## carambola5

screenie:

```

#!/bin/bash

PICPATH=$HOME/pictures/screenshots

INDEX=`cat $PICPATH/index.dat`

import -window root $PICPATH/ss$INDEX.png

echo $(($INDEX + 1)) > $PICPATH/index.dat

```

I mapped this to my printscreen key through .fluxbox/keys

----------

## H-Pi

nice thread!

```
alias es='emerge -s'

alias ep='emerge -p'

alias ue='ACCEPT_KEYWORDS="~x86" emerge'
```

Ihated to type ACCEPT_KEYWORDS="~x86, and didn't want to put it in my make.conf so made an alias for it, and then thought: why not es and ep too?

 *Quote:*   

> 
> 
> I find it remarkable how many people don't use the history command. 
> 
> 

 

I just use the tab, page-up and page-down buttons, they take away the need of an 'history'Last edited by H-Pi on Tue Jan 14, 2003 10:52 pm; edited 2 times in total

----------

## red_over_blue

```

alias recal='history | grep'

```

You can then just type

```

!955

```

Supposing 955 was the line you wanted to execute again.  I also like using ctrl-l for clear (screen) and ctrl-d to log-out.

----------

## sa

```

alias play-dvd='xine --auto-play -s dvd'

xnest='Xnest -auth .Xauthority_blah -full -sync -name "Xnest :1" -fp `xset -q | grep fonts` :1'
```

 :Smile: 

----------

## frew

Wow, history really is useful...Can't beleive I've never seen it before.

I know this is useless but I like it:  (btw, you have to emerge cowsay first)

```

date +%l:%M| cowsay

```

I can't think of anything else at the moment...

Oh yeah, and put that in the begginging of .bashrc

----------

## zojas

I use history substitution a lot. not only '!!' to repeat the last command, !23 to repeat command number 23, and !c to repeat the last command which started with 'c', but you can also use '!$' to get the last word from the previous command. so say you wanted to check for a package in the mask file, then edit it:

```
grep kde /usr/portage/profiles/package.mask

vim +/kde !$

```

before I started using etc-update I used to do this a lot:

```

diff net.eth0 ._cfg000.net.eth0

mv !$ !^

```

(!^ means the first argument of the previous command)

also !* means all the arguments from the previous command (without the program name)

```
diff net.eth0 ._cfg000.net.eth0

vim -o !*

```

also I make an alias called 'h' for the word 'history'

----------

## Empty_One

dumb question, but how is the hisory better than just cycling through the list with the up arrow?  Seems like you would have to read thru the list anyway

----------

## zojas

with history you see it all at once. the eye travels faster than the fingers! try it, once you do it a few times you'll see.

----------

## H-Pi

but why not just type the first few characters and then press Page Up to scroll trough the history of that particular thing? seems faster to me as finding a number and type !number

----------

## zojas

 *H-Pi wrote:*   

> but why not just type the first few characters and then press Page Up to scroll trough the history of that particular thing? seems faster to me as finding a number and type !number

 

sometimes I do just scroll up.  it depends though.

here's an example where typing 'h' (which is aliased to 'history') and then !number is a lot easier than searching backward for the leading substring:

```

    32  9:43    make && make install && pu && make

    33  9:43    gvim source_stat.cpp

    34  9:44    make

    35  9:46    make

    36  9:47    make

{now imagine an arbitrary number of more 'make's}

    37  9:47    pu

    38  9:47    h

!32

```

for all the little makes, I typically just hit the up arrow and enter or !m

but when I need to do the long make command again (which rebuilds a library) then it's time to pull up the history.

btw, 'pu' is an alias for 'pushd'. the directory stack is another cool feature best explained in the man page.

----------

## red_over_blue

Also, look at my alias for "recal"

```

alias recal='history | grep"

```

Now suppose you want to see a list of all the commands you just typed that contain "scp" for example

```

recal scp

```

Then just pick the one you were looking for out of the list.  The history command used just by itself is not that powerful, but piping it to grep or some other filter is where things get interesting.

----------

## zojas

also I do stuff like this:

```
rsync -uav junk cash sheets rav:~

rsync -uav rav:~/\{cash,sheets,junk\} .

```

then later if I want to do it again, I can simply do this:

```

h

!12 && !13

```

then later now that I've combined them I can do

```

!rs

```

(i could probably just type '!r' but I don't like to do that in case I have any stray 'rm' commands in the history   :Shocked: )

----------

## really

```
alias ls="ls -ls --color"

alias killshit="killall -9 wine;killall -9 wineserver"

alias kazaa="cd ~/fakewin/Program\ Files/KaZaA\ Lite/;wine Kazaa.exe"

```

ctrl+r and you do a "reverse search" 

saves typing the arrowkey up to search for some long command your lazy to type again,  :Wink: 

i also have "ugasi" in roots .bashrc which means turnoff on coratian.

alias ugasi="shutdown -h now"

im usually very tired in the morning (03:30) and dont want to type that command...  :Very Happy: 

(i have to switch to dvorak soon.)

----------

## zojas

 *antonik wrote:*   

> 
> 
> (i have to switch to dvorak soon.)

 

I have these aliases:

```

alias asdfg='loadkeys dvorak'

alias aoeui='loadkeys us'

```

for switching keymaps on the console. it uses the home row keys on the left hand in each keymap. (if you're in 'us', then the home keys are asdf, and typing them gets you to 'dvorak')

I have aliases for 'aoeu' and 'asdf' for toggling the map in X.

----------

## really

 *zojas wrote:*   

>  *antonik wrote:*   
> 
> (i have to switch to dvorak soon.) 
> 
> I have these aliases:
> ...

 coool tip  :Cool: 

----------

## tactless

Okay, here's one for resuming wget transfers by their log files: ($1 being the log file)

```
function wgetresume {

        wget -ba $1 `head -n 1 $1 | sed s/^[0-9\ :-]*//g`

}
```

I've just learned regular expressions... please tell me if there's any way to improve this.

----------

## Sven Vermeulen

Next is in ~/.inputrc:

```

"\e[[A":"\C-Aman \C-M"

"\e[[B":"mutt\C-M"

"\e[[C":"slrn\C-M"

"\e[[D":"links www.google.com/linux\C-M"

"\e[[E":"startx\C-M"

```

These aren't aliases, but shortcuts.

F.i.

```

~$ ps

```

(without return) and pressing "F1" will evoke the ps manpage. Issuing F2 starts mutt, F3 slrn, F4 links and F5 startx.

Very handy !

----------

## Munck

Unix Guru Universe has a mailing list that sends one command line tip to your mailbox everyday. You can also see them on their homepage.

Worth checking out.

http://www.ugu.com/sui/ugu/show?tip.today  :Cool: 

----------

## S_aIN_t

 *Empty_One wrote:*   

> dumb question, but how is the hisory better than just cycling through the list with the up arrow?  Seems like you would have to read thru the list anyway

 

when cycling you have to press up all the time to get to the next command. with history you can grep it to find the command you are looking for and excute it. it is especially nice when you are currently at command 1234 and you remember typing out something really long a few hours ago. so you grep history for a portion of that really long command. it will return the number of the command and you can execute the really long command again  :Smile: 

it would be nice to bind a key to "history|grep $var" so when you are at the console. however, i am not sure how to map keys with bash.

----------

## sa

 *S_aIN_t wrote:*   

> 
> 
> it would be nice to bind a key to "history|grep $var" so when you are at the console. however, i am not sure how to map keys with bash.

 

try typing "CTRL r" then start typing the command. It will autocomplete it from what you have written in your history file.

----------

## hooligan

I worked with sco for awhile, and got used to these

```

alias ls="ls --color"

alias l="ls -latr --color"

alias la="ls -a --color"

```

then there are these... just other easy ones

```

alias untar="tar -xvzf"

alias kernlconf="make dep && make clean bzImage modules modules_install"

```

----------

## steveb

 *hooligan wrote:*   

> I worked with sco for awhile, and got used to these
> 
> ```
> 
> alias ls="ls --color"
> ...

 

how about this one?

```
alias kernlconf="if [ ! -f ./Makefile ];then echo -ne '\a\n\\033[1;31mYou must bin in the kernel directory to execute this command.\\033[0;39m\n\n';else make dep && make clean && make bzImage && make modules && make modules_install && export kernel_ver=\$(grep -i '^VERSION[ ]*=' Makefile|sed -n 's/.*[ ]*=[ ]*\(.*\)/\1/gIp').\$(grep -i '^PATCHLEVEL[ ]*=' Makefile|sed -n 's/.*[ ]*=[ ]*\(.*\)/\1/gIp').\$(grep -i '^SUBLEVEL[ ]*=' Makefile|sed -n 's/.*[ ]*=[ ]*\(.*\)/\1/gIp')\$(grep -i '^EXTRAVERSION[ ]*=' Makefile|sed -n 's/.*[ ]*=[ ]*\(.*\)/\1/gIp');mount /boot;for i in vmlinux System.map .config;do cp -i ./\$i /boot/\${i}-\${kernel_ver};done;for i in bzImage;do cp -i ./arch/i386/boot/\$i /boot/\${i}-\${kernel_ver};done;unset kernel_ver;umount /boot;fi"
```

cheers

SteveB

----------

## Lactic

 *carambola5 wrote:*   

> Yes, we all know how to alias stuff in /etc/profile or ~/.bashrc or whatever.  Some favorites of (seemingly) everyone are:
> 
> ```
> alias ls='ls --color'
> 
> ...

 

Here's mine:

```
alias d="ls --color"

alias ls="ls --color"

alias sl="ls --color -lA"

alias ll="ls --color -l"

alias la="ls --color -lA"

alias rd="rmdir"

alias md="mkdir"

alias cd..="cd .."
```

----------

## zypher

Just one I always do at first and can't understand why it never made into a standard /etc/profile:

```
alias updatedb="updatedb --prunepaths='/dev /mnt /proc /tmp /usr/src /usr/portage /var/tmp'"
```

----------

## drakonite

 *zypher wrote:*   

> Just one I always do at first and can't understand why it never made into a standard /etc/profile:
> 
> ```
> alias updatedb="updatedb --prunepaths='/dev /mnt /proc /tmp /usr/src /usr/portage /var/tmp'"
> ```
> ...

 

There are quite a few people who want /mnt /usr/src and /usr/portage to be in the locate database.  /tmp and /var/tmp are pruned by default, and I think /dev and /proc are as well but I don't know for sure about that...  What would be really nice to have in /etc/profile would be to have it prune out /bin and /usr  .... Those put way too many files in the database  :Wink: 

My tip...

I find it very useful to have a script that looks something like the following:

```

#!/bin/bash

nice emerge rsync

nice emerge -up world

date

rdate -sup time.nist.gov

```

which updates the portage tree, spits out all of the updates that would be done, then syncs the time, echoing both previous and new time to let you see how much the time was adjusted by.

Meh... I know it's not much but it's saves me a lot of typing..

----------

## nephros

speaking of history, the ^R (Ctrl-R) command does also have its uses, just hit it and type away whatever you are searching for.

Now for something completely different. I got tired of typing tar -xjf boo.tar.gz and vice versa, so I wrote this (I call it untar):

```

#!/bin/bash

TAR=$(which tar)

UNZIP=$(which unzip)

RAR=$(which rar)

if [ ! -e $1 ]; then

   echo "no filename given"

   exit 1

fi

# returns gzip, bzip2 or Zip

TYPE=$(file $1 | cut -d " " -f 2)

NOEXT=$(echo $1 |cut -d "." -f 1)

if [ $TYPE == "gzip" ]; then

  $TAR -xzf $1

elif [ $TYPE == "bzip2" ]; then

  $TAR -xjf $1

elif [ $TYPE == "Zip" ]; then

  echo file is a .zip!

  unzip -d $NOEXT $1

elif [ $TYPE == "RAR" ]; then

  echo file is a .rar!

  rar x $1 $NOEXT

fi

echo done.

```

far from perfect, I know, but it works (not having it done with a "case $TYPE in" bugs me a bit, but after all laziness is a virtue or a sysadmin. Also, I should probably refresh my sed and awk knowledge.

----------

## ViCToR:

 *carambola5 wrote:*   

> screenie:
> 
> ```
> 
> #!/bin/bash
> ...

 

My two cents: I have this in my .fluxbox/keys

```
Mod1 F12 :ExecCommand import -window root /home/httpd/htdocs/shots/screenshot-`date +%m%d%H%M%S`.png
```

Which takes a screenshot, names it with the current timestamp and puts it directly on a public path for www access.

----------

## iKiddo

Which package does "import" belong to?

----------

## Kaali

Less known feature in 'ls' that is in par with "--color". 

`ls -F`, Suffix  each  directory  name with `/', each FIFO name with `|', and each name of an executable with `*'.

----------

## carambola5

 *iKiddo wrote:*   

> Which package does "import" belong to?

 

ImageMagick (in portage: imagemagick)

Comes with a bunch of useful tools such as "import" and "convert."  

If you want to create your own bootsplash images ala "Tip of the Year," you're gonna need convert to downsize your color depth.

Of course, import is the screenshot taker.

While you're at it, grab fbgrab from portage too.  It does the same thing as import, but only for the console (framebuffer).

----------

## Jimbow

Many great ideas.  I learned a lot.  Thanks.  Here are some of mine:

```
#-------- long ls listings /w pager --------

function ll  { ls -lF   $@ | more;}

function lla { ls -lAF  $@ | more;}

function llt { ls -lAFt $@ | more;}

#-------- Clean: removes emacs *~ and #*# files --------

function clean {

    if [[ "$#" == "0" ]] ; then set '.'; fi;

    for dir in $@; do

        if [[ -d $dir ]]; then

            rm -f ${dir}/*~ $dir/#*#;

        else

            echo "clean: missing directory '${dir}'"

        fi

    done;

}

#-------- ls -F if directory, less if file --------

function li {

    if [[ -d $1 ]] ; then

         ls -F $1;

    elif [[ -f $1 ]] ; then

        less $1;

    else

        ls -F $1

    fi

}
```

----------

## iKiddo

 *carambola5 wrote:*   

> While you're at it, grab fbgrab from portage too.  It does the same thing as import, but only for the console (framebuffer).

 

Thanks, I figure the framebuffer should be enabled (kernel/USE/etc.) to use fbgrab? (I don't have them enabled, had some bug switching between X and VCs.)

----------

## jleidigh

Use CTRL-R for reverse text matching search against history, better than seeing all the output of history if you have an idea of the command previously executed but are unsure of the syntax and definitly better than using the up arrow

----------

## Caffeine

 *NiklasH wrote:*   

>  *wbsoft wrote:*   
> 
> ```
> 
> nd() { test -d "$1" || mkdir "$1" && cd "$1" ; }
> ...

 

I'm having the same problem. What's the correct entry in Xaccess?

----------

## Jarjar

For killing wine(x) when it ... fucks up.

```

/usr/bin/killall-that-contains: (can't think of a name; help me!)

#!/bin/sh

if [ $1 == "-9" ]

then

        for i in $(ps aux|grep $2|grep -v grep|cut -c10-15)

        do

                kill -9 $i

        done

else

        for i in $(ps aux|grep $1|grep -v grep|cut -c10-15)

        do

                kill $i

        done

fi

```

Warning: Bash scripting newbie.  :Very Happy: 

The only alias I use, except for ll/ls (--color=yes --show-control-chars) is

alias startx='startx -- -dpi 100'

Edit: Oopsie! I reversed the if and else; it kill -9'ed if you told it not to and the other way around...fixed.

----------

## guero61

My few toys that are useful outside of the private networks I use --

```

alias psg="ps -awef |grep"

alias psu="ps -u"

alias ct="tar -cvzf"

alias xt="tar -xvpf"

alias xzt="tar -xvzpf"

alias xjt="tar -xvjpf"

alias ll="ls -lF --color"

alias lla="ls -laF --color"

alias r="fc -s"

set -o vi

```

Those, and I love using "cd -", it saves so much typing!

----------

## Jimbow

Here are some (hopefully) non-dups:

```

alias snice="sudo nice -n 5"

alias smerge="snice emerge"

alias kern="snice make dep && snice make clean bzImage modules modules_install"

loc () {

    locate -i $@ | grep -v ^/usr/portage | grep -v ^/var

}

burn () {

    sudo cdrecord -v speed=4 dev=0,0,0 -data $1

}

start () {

    nohup $@ &

}

#-------- long ls listings /w pager --------

ll  () { ls -lF   $@ | more;}

lla () { ls -lAF  $@ | more;}

llt () { ls -lAFt $@ | more;}

#-------- clean: removes emacs *~ and #*# files --------

clean () {

    if [[ "$#" == "0" ]] ; then set '.'; fi;

    for dir in $@; do

        if [[ -d $dir ]]; then

            rm -f ${dir}/*~ $dir/#*#;

        else

            echo "clean: missing directory '${dir}'"

        fi

    done;

}

#-------- li: ls -F if directory, less if file --------

li (){

    if [[ -d $1 ]] ; then

         ls -F $1;

    elif [[ -f $1 ]] ; then

        less $1;

    else

        ls -F $1

    fi

}
```

----------

## Yarrick

```
ls -h
```

 can also be useful. It displays file sizes as human-readable, using giga/mega/kilo/bytes for size instead of just bytes.

somtimes i miss an alias to mkdir && cd a new folder... havent written one yet though.

----------

## morgap98

i can't get my laptop to parse the .bashrc file.  The only time that i can make changes to my bash prompts are through the /etc/profile script.

NOTE: if i type "bash" [enter] then it will parse my .bashrc,

how can i get this to automatically happen, i don't think i should be modifiying my /etc/profile script like this!!!

</P33T>

----------

## BackSeat

For those unfamiliar with ^R reverse search in bash, here's an extra tip. After ^R type a few characters and the command line that contained those characters will be shown. Type ^R again at that point, and the search will continue back through the history.

For those aliasing ls='ls --color' you might prefer to use

```
lss='ls --color=auto'
```

That way the coloUr escape sequences are only sent if the output is connected to a terminal (so sending the output of ls to a file doesn't result in embedded escape sequences.

In a similar way, I alias grep:

```
alias grep --color-auto
```

which highlights the matching pattern in the output. Try it: you'll never want to be without it.

Finally (for now), if you think 'less' is just a way of paging through a file, read the man page. There is more flexibility in this program than a lot of people realise.

BS

----------

## Redson

 *tactless wrote:*   

> Not really a "trick", but here's something I put in my bashrc:
> 
> ```
> fortune
> ```
> ...

 

That is awesome!  You inspired me to write my first pseudo bash script!!!!

It essentially picks a certain type of fortune depending on what day it is.

I put it in my bashrc:

```
NUMBER_OF_FORTUNES=3

DATE=`eval date +%d`  #Produces only the date Number.

let "DATE=$DATE%$NUMBER_OF_FORTUNES"

case "$DATE" in

   [0]  ) fortune;; #Random fortune

   [1]  ) fortune /usr/share/fortune/starwars;;  #Quoute from Star Wars

   [2]  ) fortune /usr/share/fortune/homer;;  #Quote from Homer

esac
```

note that to do this you need to 

emerge fortune-mod-homer

emerge fortune-mod-starwars

I would also recommend doing emerge -s fortune for a list of other cool fortune files.

----------

## Redson

 *morgap98 wrote:*   

> i can't get my laptop to parse the .bashrc file.  The only time that i can make changes to my bash prompts are through the /etc/profile script.
> 
> NOTE: if i type "bash" [enter] then it will parse my .bashrc,
> 
> how can i get this to automatically happen, i don't think i should be modifiying my /etc/profile script like this!!!
> ...

 

Hello fellow N00B!  I had this problem for a while, fortunately somebody finally told me you have to put 

```
[ -f ~/.bashrc ] && source ~/.bashrc
```

at the end of your .bash_profile so it reads your .bashrc

After doing that I think you have to do 

```
source .bash_profile

env-update
```

though I'm not sure about that.  Then remember to restart your shell before the .bashrc takes effect

----------

## ebrostig

Since we are all sharing and beeing very happy in this thread, I thought I was going to add to the confusion  :Cool: 

Here is my .bash_profile

```

alias ls="ls --color=auto"

alias l="ls -l "

alias lm="ls -l| more"

alias la="ls -a "

alias llm="ls -la | more"

alias ln="ls -lLt | more"

alias cdo="cd $ORACLE_HOME"

## LS_COLORS should be on one line, broken up here as not to mess up phpBB too much :)

export LS_COLORS='no=00:fi=00:di=01;34:ln=00;36:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:

or=40;31;01:ex=00;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;31:*.z=01;31:

*.Z=01;31:*.gz=01;31:*.bz2=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.jpg=01;35:*.jpeg=01;35:

*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:

*.tif=01;35:*.tiff=01;35:*.png=01;35:*.mpg=01;35:*.mpeg=01;35:*.avi=01;35:*.fli=01;35:*.gl=01;35:

*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.ogg=01;35:*.mp3=01;35:*.wav=01;35:';

alias grep="grep --color=auto"

shopt -s cdspell 

shopt -s cdable_vars

shopt -s checkhash 

shopt -s checkwinsize 

shopt -s mailwarn

shopt -s sourcepath

shopt -s no_empty_cmd_completion

shopt -s histappend histreedit

shopt -s extglob

shopt -s extglob   # necessary

complete -A hostname   rsh rcp telnet rlogin r ftp ping disk ssh

complete -A command    nohup exec eval trace strace gdb

complete -A command    command type which 

complete -A export     printenv

complete -A variable   export local readonly unset

complete -A enabled    builtin

complete -A alias      alias unalias

complete -A function   function

complete -A user       su mail finger

complete -A helptopic  help   # currently same as builtins

complete -A shopt      shopt

complete -A stopped -P '%' bg

complete -A job -P '%'     fg jobs disown

complete -A directory  mkdir rmdir

complete -f -X '*.gz'   gzip

complete -f -X '!*.ps'  gs ghostview gv

complete -f -X '!*.pdf' acroread

complete -f -X '!*.+(gif|jpg|jpeg|GIF|JPG|bmp)' xv gimp

function lowercase()  # move filenames to lowercase

{

    for file ; do

        filename=${file##*/}

        case "$filename" in

        */*) dirname==${file%/*} ;;

        *) dirname=.;;

        esac

        nf=$(echo $filename | tr A-Z a-z)

        newname="${dirname}/${nf}"

        if [ "$nf" != "$filename" ]; then

            mv "$file" "$newname"

            echo "lowercase: $file --> $newname"

        else

            echo "lowercase: $file not changed."

        fi

    done

}

function xtitle () 

{ 

    case $TERM in

   xterm* | dtterm | rxvt) 

       echo -n -e "\033]0;$*\007" ;;

   *)  ;;

    esac

}

alias top='xtitle Processes on $HOST && top'

alias eworld='xtitle Emerge update world && emerge -u --deep world'

alias esync='xtitle Emerge rsync in progress && emerge rsync'

alias ncftp="xtitle ncFTP ; ncftp"

alias splus="xtitle SQL*Plus && sqlplus \"/ as sysdba\""

```

Erik

----------

## balk

 *BackSeat wrote:*   

> 
> 
> Finally (for now), if you think 'less' is just a way of paging through a file, read the man page. There is more flexibility in this program than a lot of people realise.
> 
> BS

 

How often I press '/' in any other program when trying to search for a word! Should be implemented in every browser too. Less rules

I also curse on Windows when I try to alt-drag a window... nice features

----------

## grant.mcdorman

 *NiklasH wrote:*   

>  *wbsoft wrote:*   
> 
> ```
> 
> nX()
> ...

 

You need to do several things to get this to work.

First off, most display managers - especially kdm and gdm - are configured to ignore the -query (technically, it's XDMCP Query). You need to modify your window manager configuration file.

Display manager configuration

For kdm, it is in /usr/kde/3.1/share/config/kdm/kdmrc (the 3.1 will vary, of course, if you're running a release other than 3.1.x). In this file you will find: 

```
[Xdmcp]

# Whether KDM should listen to XDMCP requests. Default is true.

#Enable=false

# The UDP port KDM should listen on for XDMCP requests. Don't change the 177.

#Port=177

# File with the private keys of X-terminals. Required for XDM authentication.

# Default is ""

#KeyFile=/usr/kde/3.1/share/config/kdm/kdmkeys

# XDMCP access control file in the usual XDM-Xaccess format.

# Default is /usr/kde/3.1/share/config/kdm/Xaccess

# XXX i'm planning to absorb this file into kdmrc, but i'm not sure how to

# do this best.

Xaccess=/etc/X11/xdm/Xaccess

```

Make sure that the 'Enable=false' line is commented out, and the 'Xaccess=/etc/X11/xdm/Xaccess' is not commented out.

For gdm, please check this next section; I don't have gdm installed. However, according to the online references I can find, its configuration files are in /etc/gdm/Init/gdm.conf.

In this file, set it up as follows: 

```
[xdmcp]

Enable=1

```

I can't see a configuration for Xaccess, so presumably it uses the standard one.

Xaccess configuration

For most purposes, you just need to add the following line to /etc/X11/xdm/Xaccess:

```
*
```

That's it (one asterix). You can make it more restrictive - the comments in the file should be adequate.

The nX function should now work.

Note, by the way, that there is a hole in this script: the presence of the /tmp/.Xn-lock is not a 100% guarantee that there's a server running, as this file might be left around if the server crashes.

Important: Firewalling

Be sure to have UDP port 177 closed on your firewall (if it's a sensible firewall, you have to explicitly open ports). The protocol used - XDMCP - is not that secure; in addition, if you use the Xaccess setup I've suggested your display manager will offer login windows to any X display - including random unknown ones on the Internet, if they can get at ports 177 and 6000 on your machine.

----------

## nephros

oh well, I might just add to that:

```

alias dir="echo NO SUCH FILE OR DIRECTORY"

alias x="startx"

alias y="startx -- :1"

alias h="history"

alias ..="cd .."

alias cd..="cd .."

alias ...="cd ~"

alias nano="nano -w -T 4"

alias pico="nano -w -T 4"

```

and for root:

```

alias unmerge="emerge unmerge"

alias semerge="screen emerge"

```

also note that you can prefix any command with a \ backslash to escape any aliases you have set. So \pico would launch a real pico instead of the nano alias...

----------

## flickerfly

 *nitro322 wrote:*   

> If you haven't noticed, the left and right windows keys on your keyboard will change you to the virtual terminal to the left and right of your current one.  Nice.

 

How?  I use fluxbox, you?

----------

## carambola5

 *flickerfly wrote:*   

>  *nitro322 wrote:*   If you haven't noticed, the left and right windows keys on your keyboard will change you to the virtual terminal to the left and right of your current one.  Nice. 
> 
> How?  I use fluxbox, you?

 

For fluxbox, put this in your ~/.fluxbox/keys

```
...

None Super_R :NextWorkspace

None Super_L :PrevWorkspace

...
```

Other fun keys mods are (assuming a multimedia keyboard):

```
None XF86AudioPlay :ExecCommand xmms -t

None XF86AudioStop :ExecCommand xmms -s

None XF86AudioPrev :ExecCommand xmms -r

None XF86AudioNext :ExecCommand xmms -f

None XF86AudioLowerVolume :ExecCommand ~/bin/changevol d

None XF86AudioRaiseVolume :ExecCommand ~/bin/changevol u

None Print :ExecCommand ~/bin/screenie

```

where changevol is (I removed my muting code because I'm not sure if it works or not):

```
#!/bin/bash

case $1 in

  "d") aumix -v-2

    ;;

  "u") aumix -v+2

    ;;

  "*") echo "Error"

esac
```

and screenie is:

```
#!/bin/bash

PICPATH=$HOME/pictures/screenshots

if [ -f "$PICPATH/index.dat" ]; then echo 1 > $PICPATH/index.dat; fi

INDEX=`cat $PICPATH/index.dat`

import -window root $PICPATH/ss$INDEX.png

echo $(($INDEX + 1)) > $PICPATH/index.dat
```

(I think that'll work)

----------

## Brandy

 *klieber wrote:*   

> I find it remarkable how many people don't use the history command.  That, combined with the '!n' to re-issue a frequently-used command saves me tons and tons of time.
> 
> 

 

I agree. The history is sometimes very useful. You can also use it to fix spelling mistakes.  :Smile: 

Let's say you want to add a new user:

```
root@dante / # usradd -m -c "Brandy Westcott" brandy -g users -G wheel,portage -s /bin/bash

bash: usradd: command not found
```

hmm... bad spelling. No problem:

```
^sr^ser

useradd -m -c "Brandy Westcott" brandy -g users -G wheel,portage -s /bin/bash
```

^string1^string2 is really just the same as !!:s/string1/string2

Ciao, Brandy

----------

## flickerfly

 :Idea:   *carambola5 wrote:*   

> 
> 
> ```
> ...
> 
> ...

 

Thanks, I don't have a multimedia keyboard here though.  This will be nice to work with and I'll keep the multimedia stuff in memory for later.  Thanks.    :Very Happy: 

----------

## burmashave

Wow, this is a superb thread!  I've been using Linux for about 2 years now; however, I couldn't figure out how the power users got by without using some gui tools.

I've added "history" and "ls" commands to my bashrc, and also added fortune.  Thanks for all the above suggestions.

I often find myself grepping about for files, and the only find command I can remember is "find --iname", so I wrote a script to handle my find operations:

```
#! /bin/sh

# findfile -- a utility for finding files and directories

PATH=/usr/bin:/bin; export PATH

case $1 in 

   fn) find -iname $2 -print 2>/dev/null | more;;

    fs) find -size +$2k -print 2>/dev/null | more;;

    fm) find -cmin -$2 -print 2>/dev/null | more;;

    fd) find -iname $2 -type d -print 2>/dev/null | more;;

    fds) du -m * 2>/dev/null | sort -rn | head -$2;;

    ffs) PERCENTAGE=$2

      df -kl | grep -iv filesystem |  awk '{  print $6" "$5} '| while

          read LINE; do

           PERC=`echo $LINE | cut -d"%" -f1 | awk '{  print $2 } '`

           if [ $PERC -gt $PERCENTAGE ]

               then

             echo $LINE  

           fi

            done;;

   fbad) find . -type l -print 2>/dev/null | perl -nle '-e || print';;

    f) echo "findfile usage:"

       echo 

      echo "fn <name>   find file <name>, case insensitive, errors suppressed, wildcards OK"

      echo "fs <n>      find file greater than <n> kilobytes"

      echo "fm <n>      find file modified within last n minutes"

      echo "fd <name>   find directory <name>, case insensitive"

      echo "fds <n>     find top <n> directories, based on diskspace usage (in megabytes)"

      echo "ffs <n>     find file systems with usage greater than <n> percent"

      echo "fbad        find bad symlinks"

      echo "f           list findfile options"

      echo

    esac

```

Then, I added the following aliases to bashrc:

```
alias fn="findfile fn"

alias fs="findfile fs"   

alias fm="findfile fm"

alias fd="findfile fd"   

alias fds="findfile fds"

alias ffs="findfile ffs"

alias fbad="findfile fbad"

alias f="findfile f"

```

I put the findfile script in PATH, and now I can find files using a short command, or simply enter "f" to get a list of my find options:

```
admin@cruise admin $ f

findfile usage:

 

fn <name>   find file <name>, case insensitive, errors suppressed, wildcards OK

fs <n>        find file greater than <n> kilobytes

fm <n>        find file modified within last n minutes

fd <name>  find directory <name>, case insensitive

fds <n>       find top <n> directories, based on diskspace usage (in megabytes)

ffs <n>       find file systems with usage greater than <n> percent

fbad            find bad symlinks

f                 list findfile options

```

As my title implies, I am a noob, so I would welcome any suggestions about my script.

Another thing I put in bashrc is an alias for my SSH connections:

```
alias myserver="ssh -l admin xxx.xxx.xxx.xxx" # ssh to server
```

If you're using a key to authenticate, the command "myserver" will automatically initiate a session.

----------

## thadk

Quick Question: How can you make any process run like a daemon. I.e. how can you run a process and then close the xterm window or ssh session and still have the process run in the background.

Also I have a tip: To search through files looking for specific content you can use:

```

$ find . -exec grep -H [search-string] {} \;

OR

$ grep -R [search-string] *
```

----------

## scap1784

```
alias burn="cdrecord -vv speed=8 dev=0,0,0  -eject "

```

I also made a few 4 letter words aliases for fortune so when my friends get on here and get mad at the computer it talks back! kinda a stress reiliver i guess

----------

## viperlin

probably THE most usefull one ever:

```

alias lsd="ls --color -d */"

```

try it, it's lovely and really usefull in those massive directory's.

----------

## vers_iq

 *Empty_One wrote:*   

> dumb question, but how is the hisory better than just cycling through the list with the up arrow?  Seems like you would have to read thru the list anyway

 

The function of history is not only to repeat a certain command, but it's most useful to keep track the chain of command line in certain console. expecially if u are in the middle of a task which requires u to enter command inputs in particular order.

----------

## Bellrang QT

Probably another dumb question...

Is there a way to control what shows up in the titlebar of Putty?  When I emerge (using an ssh session with Putty), the titlebar is changed.  When emerge is done, the titlebar just displayed "xterm".

When I ssh into my RedHat box, it shows user@machine... that's kinda nice.

Any ideas?

----------

## nico--

 *thadk wrote:*   

> Quick Question: How can you make any process run like a daemon. I.e. how can you run a process and then close the xterm window or ssh session and still have the process run in the background.
> 
> 

 

Use &:

```
mpg123 mylegallyrippedmp3file.mp3 &
```

If you leave the xterm open you still get output from the program... you have to redirect the output to /dev/null but i can't remember how to do that, heh.

----------

## thadk

No, I'm pretty sure that a backgrounded(&) process dies when it's parent (the xterm/ssh session) does. I'm trying to figure out how to make it so the parent is pid 1 (at least thats the definition of a daemon I found)

With kde I can sort of do what I want with `kdeinit`

----------

## lisa

Here's mine...

```

alias nano='nano -w'

alias rm='rm -i'

alias mv='mv -iv'

alias cp='cp -iv'

alias ls='ls --color=auto'

alias rndc='rndc -k /chroot/dns/etc/bind/rndc.key'

export PS1='\[\033[01;32m\]\u@\h \[\033[01;34m\]\W \$ \[\033[00m\]'

case $TERM in

        xterm*|rxvt|eterm)

                PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME%%.*}:${PWD/$HOME/~}\007"'

                ;;

        screen)

                PROMPT_COMMAND='echo -ne "\033_${USER}@${HOSTNAME%%.*}:${PWD/$HOME/~}\033\\"'

                ;;

esac

```

 :Smile: 

This along with bash-completion makes my life easier.

----------

## Ivion

 *thadk wrote:*   

> No, I'm pretty sure that a backgrounded(&) process dies when it's parent (the xterm/ssh session) does. I'm trying to figure out how to make it so the parent is pid 1 (at least thats the definition of a daemon I found)
> 
> With kde I can sort of do what I want with `kdeinit`

 

Well, 1 option is screen, with which you can 'detach' processes and they will keep running even if you log out. And you also have the ability to 'retach' processes.  :Smile: 

Another option is:

```

(program &)

```

This 'disowns' a process, this actually starts the program in a subshell, and puts the program inside that subshell into the background. ^_^

I'm not sure if this will work with what you want to accomplish, but I'm sure screen will.  :Very Happy: 

----------

## isomer

 *thadk wrote:*   

> No, I'm pretty sure that a backgrounded(&) process dies when it's parent (the xterm/ssh session) does. I'm trying to figure out how to make it so the parent is pid 1 (at least thats the definition of a daemon I found)

 

Try this:

```
$ nohup /path/to/program
```

The program you start won't be killed by the HUP signal that way, and will live on even if its xterm is closed.

  -isomer

----------

## thadk

I think I recall reading bout that somewhere now but it got lost.

----------

## viperlin

in an aterm/xterm/eterm and others backgrounding something will stay after you close it if you close it by pressing CTRL-D instead of using the window manager exit button, or at least it does for me.

----------

## Bellrang QT

 *nico-- wrote:*   

> If you leave the xterm open you still get output from the program... you have to redirect the output to /dev/null but i can't remember how to do that, heh.

 

```
mpg123 mylegallyrippedmp3file.mp3 > /dev/null &
```

 *I wrote:*   

> Probably another dumb question... 
> 
> Is there a way to control what shows up in the titlebar of Putty? When I emerge (using an ssh session with Putty), the titlebar is changed. When emerge is done, the titlebar just displayed "xterm". 
> 
> When I ssh into my RedHat box, it shows user@machine... that's kinda nice. 
> ...

 

Any ideas about this yet?

----------

## Kalin

Just saw this thread, so here are my aliases:

```

alias ll='ls -l --color=always'

alias emerge='emerge -v'

alias merge='ACCEPT_KEYWORDS=~x86 emerge'

alias unmerge='emerge unmerge'

alias nano='nano -w'

# Commands I cannot remember are stored here

alias h='less /usr/local/doc/commands'

# No more alsa drivers to fill the display :-)

alias llmod='lsmod |grep -v snd'

# Don't forget export GREP_COLOR="1;32" for green :-)

alias grep='grep --color=auto'

```

All this goes to /etc/profile.d/alias!

I have 

```
 [ -f /etc/profile.d/alias ] && source /etc/profile.d/alias
```

 in /etc/profile to load it for every user.

[/code]

----------

## Guezz-Who

I got a little inspired from ebrostig's tab completions so I made some more..

Notice the 'service' function.. you can type 'service pcm[tab]' and it will autocomplete it to pcmcia.. 'service pcmcia z[tab]' will autocomplete to 'service pcmcia zap'

My list of aliases/options/completions:

```
#!/bin/bash

#some vars:

GENTOO="1" #set to 1 on gentoo (i have multiple computers with different distros)

#alias:

alias ls="ls --color=auto"

alias lsd="ls --color -d */" #only dirs 

alias rm="rm -i" 

alias mv="mv -iv"

alias cp="cp -iv"

alias grep="grep --color=auto"

export GREP_COLOR="1;32" #green color grep..

alias lftp="lftp -d" #show some usefull debug info in lftp

alias recal="history | grep"

alias h="history"

alias cman="PAGER=\"cat\" man" #cat a man page..

alias psg="ps -ef | grep -v grep | grep" # ps grep

      

alias gsu="gnomesu -c"

            

alias vi="vim -o" 

alias vim="vim -o"

alias vimdiff="vimdiff -X"

alias xdiff="gvimdiff"

alias le="less"

alias mo="more"

alias mp="mplayer"

#shows what ip you have on the internet (if there's no proxys that is..

alias whatip="wget -O - http://www.whatismyip.com 2> /dev/null | grep \"<h1>\" | cut -d \" \" -f 4"

#gentoo stuff (emerge aliases and service function):

if [ $GENTOO -eq 1 ] ; then

   alias emerge="emerge -v"

   alias nemerge="nice -n 5 emerge"

   alias unmerge="emerge unmerge"

   alias aemerge="ACCEPT_KEYWORDS=\"~x86\" emerge"

   function service {  # run services from /etc/init.d/

      if [ -z $1 ] ; then

         ls /etc/init.d

      else

         /etc/init.d/$1 $2

      fi

   }

   function _listservices { # get tab completion for services and options

      local cur

      local opt

      COMPREPLY=()

      opt=${COMP_WORDS[2]}

      cur=${COMP_WORDS[COMP_CWORD]}

      if [ -z $opt ] ; then

         COMPREPLY=( $( ls -1 /etc/init.d/ | grep ^$cur ) )

      else

         COMPREPLY=( $( compgen -W 'start stop restart pause zap status' | grep ^$cur) )

      fi

   }

   complete -F _listservices service

fi

#Shell options:

shopt -s cdspell #error correction

shopt -s cdable_vars

shopt -s sourcepath

shopt -s no_empty_cmd_completion

shopt -s histappend histreedit

shopt -s extglob

shopt -s extglob

#tab completion stuff:

complete -A hostname   rsh rcp telnet rlogin lftp ftp ping disk ssh

complete -A command    nohup exec eval trace strace gdb

complete -A command    command type which

complete -A export     printenv

complete -A variable   export local readonly unset

complete -A enabled    builtin

complete -A alias      alias unalias

complete -A function   function

complete -A user       su mail finger

complete -A helptopic  help   # currently same as builtins

complete -A shopt      shopt

complete -A stopped -P '%' bg

complete -A job -P '%'     fg jobs disown

complete -A directory  mkdir rmdir

complete -f -X '!*.gz'   gunzip zcat zmore

complete -f -X '!*.bz2' bunzip2

complete -f -X '!*.zip' unzip

complete -f -X '!*.ps'  gs ghostview gv

complete -f -X '!*.pdf' xpdf

complete -f -X '!*.+(gif|jpg|jpeg|GIF|JPG|bmp)' xv gimp gqview

complete -A signal kill -P '%'

#other completions:

function _umount () {

   local cur

   COMPREPLY=()

   cur=${COMP_WORDS[COMP_CWORD]}

   COMPREPLY=( $( mount | cut -d' ' -f 3 | grep ^$cur) )

   return 0

}

function _rmmod () {

   local cur

   COMPREPLY=()

   cur=${COMP_WORDS[COMP_CWORD]}

   COMPREPLY=( $( lsmod | cut -d' ' -f 1 | grep ^$cur) )

}

function _killall () { # ps -A cut program-names if they are too long.. :(

   local cur

   cur=${COMP_WORDS[COMP_CWORD]}

   COMPREPLY=( $( ps -A | awk '{ print $4 }' | sort | uniq | grep ^$cur) )

}

complete -F _umount umount

complete -F _rmmod rmmod

complete -F _killall killall
```

----------

## Sledgy

written and/or collected over the years

```
 Add to the path variable named by $1 the component $2.  $3 must be

# "append" or "prepend" to indicate where the component is added.

addpath () {

    eval value=\"\$$1\"

    case "$value" in

        *:$2:*|*:$2|$2:*|$2)

            result="$value"

            ;;

        "")

            export $1

            result="$2"

            ;;

        *)

            case "$3" in

                p*)

                    result="$2:${value}"

                    ;;

                *)

                    result="${value}:$2"

                    ;;

            esac

    esac

    eval $1=$result

    unset result value

}

# convenience routine which appends a string to a path.

append () {

    addpath "$1" "$2" append

}

# convenience routine which prepends a string to a path.

prepend () {

  addpath "$1" "$2" prepend

}

```

allows clean scripts like:

```

...

#################################

#

#  java

#

#################################

setenv JAVA_HOME /java/j2sdk

append PATH ${JAVA_HOME}/bin

setenv CLASSPATH .

append CLASSPATH $JAVA_HOME

append CLASSPATH /java/jdom/lib/xerces.jar

append CLASSPATH /java/jdom/build/jdom.jar

...

```

```
setenv () {

  eval $1=$2

  export $1

}

```

(guess where i came from  :Wink: )

```
# tar-copy

tcp () {

  if [ $# != 2 ]

  then

    echo "usage: tcp [sourcefile|sourcedirectory] targetdirectory"

  else

    if [ ! -e $1 ]

    then

      echo "where's ${1}?"

    else

      if [ ! -d $2 ]

      then

        echo "$2 doesn't exist"

      else

        echo "/bin/tar -cvf - $1 | (cd $2; /bin/tar -xpf -)"

        /bin/tar -cvf - $1 | (cd $2; /bin/tar -xpf -)

      fi

    fi

  fi

}

```

```
# mkdir + cd

mkcd () {

  if [ $# != 1 ]

  then

    echo "usage: mcd directory"

  else

    if [ ! -d $1 ]

    then

      if [ -e $1 ]

      then

        echo "$1 exists but isn't a directory"

      else

        mkdir -p $1

        cd $1

      fi

    else

      cd $1

    fi

  fi

}

```

----------

## deurk

Woaw... The Guezz-Who one is a bit complicated for me...

Not sure I understand how everything works... Not even the half actually!

 :Laughing: 

----------

## ArsDangor

I've learned a lot from this thread  :Very Happy: 

This is my particular version of Sledgy's mkcd. It's called xmd for a DOS utility that made the same. 

It also supports a task I find very repetitive: moving some file to a directory that might not exist yet.

```
xmd () {

    if (($# > 2)) || (($# < 1))

    then

        echo "Uso: xmd directorio_nuevo [fichero de destino]"

    else

        if [ ! -d $1 ]

        then

            mkdir $1

            if (($# == 2)) && [ -e $2 ]

                then

                mv $2 $1

            fi

            cd $1

        else

            echo "El nuevo directorio ya existe o es un fichero regular."

        fi

    fi

}
```

All the ifs avoid annoying error messages from mv, cd or mkdir. The messages are in Spanish. I hope the function is simple enough not no need them translated.  :Wink: 

----------

## semiSfear

My .bashrc prompt can be found here: https://forums.gentoo.org/viewtopic.php?t=75940

----------

## dylix

this might of been posted, but its so great i will post it again if it has  :Razz: 

easy way to logout some people may not know about..

control-d  :Razz: 

----------

## viperlin

control-s to lock up an xterm so you cannot use it........ not usefull but i keep accidnetally doing it on my new keyboard instead of control-d, just lettin u know.....

----------

## kitano

not completely true about the control-s thingie.

yes: it locks up your xterm/eterm

no: its not a cheap screenlocker

problem: control-s is something like sleep. pressing control-w rewakens the console executing _all_ command typed in inbetween (i.d. while sleeping)

can be fatal...

don't know what its good for, anyway

----------

## kitano

nobody ever using the control-r combination?

read alot about the history command and i thought ctrl-r goes hand in hand with it...

but now that i didn't really see it here, i thought maybe i should post it.

after pressing ctrl-r, try typing the first few letters of the command which should be in your history. voila, here we go.

----------

## neenee

actually this was posted thrice already in this thread:

once one page two by sa

another time on page two by nephros

and yet another time, but this time on page 3 by jleidigh

lol.

but i won't blame anyone, since i love using it myself.

----------

## magrathea

gentoo forums keeps me up all nights with all the info everywhere... this thread is REALLY filled with good tips and tricks. 

Thank you guys for making it easy to learn more about gentoo.

----------

## Ari Rahikkala

 *kitano wrote:*   

> 
> 
> problem: control-s is something like sleep. pressing control-w rewakens the console executing _all_ command typed in inbetween (i.d. while sleeping)

 

At least on my system, it's ctrl-q, not ctrl-w... and I usually use scroll lock to cause what at least seems to be the same effect anyway.

----------

## Curious

 *Ari Rahikkala wrote:*   

> ctrl-q

 

I owe you a coke.  I keep forgetting what the turn-off-scroll-lock command is.  :Razz: 

-- Curious

----------

## byns

I changes ls to ls --color myself, but could anyone explain to me, why it somtimes works, and sometimes doesn't work (for example it's different when I "su") and sometimes the path variable is correct, buth sometimes it is not especially "/usr/local/sbin/" is oftentimes not found. Is there a list, which programs execute which files?

And the last thing that is annoying is that the keyboard rate is set to slow even if I append kbdrate to the startup programs, I have to run it manually everytime so I thought about putting it in .bashrc where it doesn't belong

----------

## carambola5

 *byns wrote:*   

> I changes ls to ls --color myself, but could anyone explain to me, why it somtimes works, and sometimes doesn't work (for example it's different when I "su") and sometimes the path variable is correct, buth sometimes it is not especially "/usr/local/sbin/" is oftentimes not found. Is there a list, which programs execute which files?
> 
> And the last thing that is annoying is that the keyboard rate is set to slow even if I append kbdrate to the startup programs, I have to run it manually everytime so I thought about putting it in .bashrc where it doesn't belong

 

You could append:

```
source /etc/profile
```

 to your ~/.bashrc file

----------

## meowsqueak

 *balk wrote:*   

> How often I press '/' in any other program when trying to search for a word! Should be implemented in every browser too.

 

Yes, I find this very handy in Mozilla. I forget when it was introduced, but it makes searching for keywords very easy.

----------

## meowsqueak

 *Brandy wrote:*   

> hmm... bad spelling. No problem:
> 
> ```
> ^sr^ser
> 
> ...

 

THAT is a mighty useful trick. Thanks! Got any more of those slightly obscure but very handy techniques?

----------

## meowsqueak

 *kitano wrote:*   

> not completely true about the control-s thingie.
> 
> yes: it locks up your xterm/eterm
> 
> no: its not a cheap screenlocker
> ...

 

Ctrl-S is the XOFF command. It disables flow control to the TTY which effectively means the controlling terminal will stop accepting output from the child process(es). It will still accept input however, you just won't see it echoed on the terminal. Any child process (or thread) that tries to write normally to the terminal will block.

Ctrl-Q is the XON command - it reverses XOFF and resumes normal behaviour.

Ctrl-S is extremely useful once you realise what it does. For example, you're downloading a file  with wget and you want to pause it. Hit ctrl-s to pause, ctrl-q to resume. As long as wget (or any other process) is constantly writing to the terminal, it will block.

Note that XOFF is not actually pausing the process, it is merely blocking stdout (the internals are a bit more complicated, but I think that's enough to get across the gist of this feature).

----------

## razamatan

i have two dandy emerge related shortcuts

```

alias lastmerge='less /var/log/emerge.last'

logmerge() { emerge $@ | tee /var/log/emerge.last; }

```

these work in concert.  logmerge logs the output of a typical emerge to /var/log/emerge.last.... then, lastmerge just less's that file.

pretty dandy when you have a -Du world that's gonna be quite long.... and quite important.

----------

## trouby

 *Quote:*   

> I forgot one very key alias in my first post:
> 
> ```
> alias pico='nano -w'
> ```
> ...

 

Ahh, I just smiled when I saw this one! this was the second command I ran when I first had my Gentoo (after the --color one)   :Laughing: 

----------

## Azaghal

 *Quote:*   

> 
> 
>  root@jaguar root # cat .bashrc
> 
> alias kernmake='echo make sure boot is mounted and old kernel images and libs are deleted && rm /usr/src/linux && ln -s /usr/src/*gentoo* /usr/src/linux && cd /usr/src/linux && make dep && make clean bzImage modules modules_install && cp /usr/src/linux/arch/i386/boot/bzImage /boot/bzImage-gentoo && emerge nvidia-kernel alsa-driver && update-modules'
> ...

 

On a side note, can you have grub boot to windows 2000 as in the example on page1 as well? or is it a lilo function only?

----------

## AgenT

 *Azaghal wrote:*   

> 
> 
> On a side note, can you have grub boot to windows 2000 as in the example on page1 as well? or is it a lilo function only?

 

I do not see why not. I do know for a fact that it will boot XP (I have done it) so it should boot 2000 as well. I think you can boot any microsoft OS, including DOS.

Try these two for more info:

```
info grub
```

Grub Manual

Example:

```

# For booting Windows NT or Windows95

title Windows 2000

root (hd0,0)

chainloader (hd0,0)+1

```

Remember that grub counts from 0, not 1. Thus hda is hd0, etc.

You can also search these forums.

----------

## Azaghal

 *AgenT wrote:*   

>  *Azaghal wrote:*   
> 
> On a side note, can you have grub boot to windows 2000 as in the example on page1 as well? or is it a lilo function only? 
> 
> I do not see why not. I do know for a fact that it will boot XP (I have done it) so it should boot 2000 as well. I think you can boot any microsoft OS, including DOS.
> ...

 

aye I have that already, but I was actually referring to this post:

 *nitro322 wrote:*   

> 
> 
> ```
> alias 2000='su -c "lilo -R 2000" && reboot'
> ```
> ...

 

Sorry for the confusion  :Smile: 

Because if I get things right, it allows you to boot into a non-default entry in the boot loader options, without having to manually select it when the bootloader loads?

And now I wonder if you can just do 'grub -R 2000' with grub too.

----------

## meowsqueak

No you can't do it simply like that (unfortunately). You have to play around with symlinks and/or copying grub.conf files and this becomes a one-way trip into He^H^HWindows unless you have some way of changing them back while running Windows... (e.g. /boot on fat32).

----------

## NoUseForAName

 *phong wrote:*   

> I have lots of aliases to save myself some typing, many are either from DOS or even from .bat files I made in the DOS days for the same purpose:
> 
> ```
> ...
> 
> ...

 

Oh, didn't know about Ctrl-L, that was nice  :Smile: 

----------

## Slinger

tag

----------

## Nice

back to this one please  :Cool: 

 *byns wrote:*   

> I changes ls to ls --color myself, but could anyone explain to me, why it somtimes works, and sometimes doesn't work (for example it's different when I "su") and sometimes the path variable is correct, buth sometimes it is not especially "/usr/local/sbin/" is oftentimes not found. Is there a list, which programs execute which files?
> 
> 

 

i too am having this problem. where is the best place to put all these nifty aliases?  in /etc/profile or in ~/.bashrc ?

i put them all in .bashrc and they do not work for root, which i would like for them to do.

 *carambola wrote:*   

> You could append: source /etc/profile to your ~/.bashrc file

  makes me think to put all alias in /etc/profile but others in this thread said not to do that i believe. 

what to do?

p.s. i figure it must come down to preference to where / how you place your aliases but a solid example would be a nice reference

----------

## meowsqueak

Place a ~/.bash_profile with the following:

```
# include .bashrc if it exists

if [ -f ~/.bashrc ]; then

    source ~/.bashrc

fi
```

Then, create your ~/.bashrc and put your aliases, exports, prompt stuff, etc in there. This will ensure your .bashrc gets processed no matter how you log in.

If you use keychain, the proper place to invoke this is .bash_profile.

For root, create similar files in /root

----------

## Nice

 *meowsqueak wrote:*   

> Place a ~/.bash_profile with the following:
> 
> ```
> # include .bashrc if it exists
> 
> ...

 

thanks meow that helps    :Cool: 

going thru my machines i noticed mdk does something similar to this by default.

----------

## Sh4d0w

My little collection:

```

alias preview "display -size 800x600"

alias show "preview"

alias resize "convert -resize 800x600"

alias rotate "convert -rotate 90 \!* \!*"

alias mflash "mount /dev/hde1 /mnt/pcmcia && cd /mnt/pcmcia/dcim/"

alias uflash "cd / && umount /dev/hde1"

alias upload 'lftp -u shadow,mypassword staff.homelan.com -e "set ftp:ssl-allow no && put -O /www/htdocs/shadow/stuff \!* && quit"'

alias nano "nano -w"

alias pico "nano -w"

alias rm "rm -f"

alias h "history"

alias hs "history | grep"

alias .. "cd .."

alias cd.. "cd .."

alias ... "cd ~"

```

Most of them are for making life with my digital camera easier....

----------

## meowsqueak

Some useful ones there, esp. the history|grep one, which I use a lot.

Btw, 'cd' does the same as 'cd ~' and it's probably quicker to type than '...' but it's up to you of course.

----------

## SubAtomic

I have noticed plenty of people retrieving their dynamic ip by using ...

```
http://www.whatismyip.com
```

This is not neccessary as your dynamic ip is already stored on your local machine once your pppd starts ...

```
currentip=`/sbin/ifconfig ppp0 | grep inet | awk '{print $2}'| awk -F : '{print $2}'`
```

----------

## viperlin

 *SubAtomic wrote:*   

> I have noticed plenty of people retrieving their dynamic ip by using ...
> 
> ```
> http://www.whatismyip.com
> ```
> ...

 

aye, but that does not work if you have cable/DSL and/or are behind a router  :Smile:  so the whatismyip one is for people in that situation  :Wink: 

----------

## vdboor

There used to be a whatismyip.org website, but it doesn't appear to be working now. That service only returned your IP, without any html code or whatsoever.

```
ip=`lynx -dump www.whatismyip.org`

ip=`links -source www.whatismyip.org`
```

----------

## AgenT

 *vdboor wrote:*   

> There used to be a whatismyip.org website, but it doesn't appear to be working now. That service only returned your IP, without any html code or whatsoever.
> 
> ```
> ip=`lynx -dump www.whatismyip.org`
> 
> ...

 

Behold the power of Linux CLI (notice how this not possible in windows): 

```
alias whatip="wget -O - http://www.whatismyip.com 2> /dev/null | grep \"<TITLE>\" | cut -d \" \" -f 4"
```

----------

## JPMRaptor

Cause I'm lazy

alias d='ls --color'

alias la='ls --color -a'

alias ll='ls --color -l'

alias lla='ls --color -al'

alias ls='ls --color=auto'

VPN via ssh tunnels.  The 10.0.0.x is the internal IP addess I'm connecting to.  The me@ssh.myco.com is the external ssh server.  Once it's connected I can access email and the intranet just like I'm there.  

alias myco-imap='screen -S imap ssh -L 10143:10.0.0.2:143 me@ssh.myco.com'

alias myco-intranet='screen -S intranet ssh -L 18080:10.0.0.8:80 me@ssh.myco.com'

alias myco-smtp='screen -S smtp ssh -L 10025:10.0.0.2:25 me@ssh.myco.com'

----------

## SubAtomic

 *viperlin wrote:*   

>  *SubAtomic wrote:*   I have noticed plenty of people retrieving their dynamic ip by using ...
> 
> ```
> http://www.whatismyip.com
> ```
> ...

 

Yes, I failed to mention that this is only for machines not contained behind a router ... thanks.

----------

## dub.wav

 *SubAtomic wrote:*   

> I have noticed plenty of people retrieving their dynamic ip by using ...
> 
> ```
> http://www.whatismyip.com
> ```
> ...

 

Or without all the unnecessary external commands: 

```
alias currentip='set `/sbin/ifconfig eth0` && echo ${7#*:}'
```

----------

## pranyi

I have recently added 

```

alias h='history | sort -k 4 | uniq -f 4 | sort -n'

```

to my .bashrc.

It is really handy.

----------

## Kalin

```
kalin@sata kalin $ cat /etc/profile.d/10alias 

alias ll='ls -l --color=always' 

alias la='ll -a' 

 

alias emerge='emerge -v' 

alias merge='ACCEPT_KEYWOEDS=~x86 emerge -p' 

alias unmerge='emerge unmerge' 

alias Dmerge='USE=debug FEATURES=nostrip ACCEPT_KEYWORDS=~x86 emerge'

alias nano='nano -w'

 

alias inject='eject -t'

# Commands I cannot remember are stored here 

alias h='cat /usr/local/doc/commands' 

# Some ls commands 

alias llmod='lsmod |grep -v snd'

alias lsmnt='mount | cut -d" " -f1,3,5,6 | sort | column -t'

 

# Don't forget echo 'GREP_COLOR="1;33"' >/etc/conf.d/88grep for yellow :-) 

alias grep='grep --color=auto' 

 

# To see those temperature signs properly in a japanese locale! 

alias sensors='sensors | iconv -f iso-8859-1 -t eucjp' 

 

# I don't like localepurge, so hacked my own

alias i18n_purge='pushd . >/dev/null 2>&1 && cd /usr/share/locale && for dir in `ls --ignore=bg* --ignore=ja* --ignore=en* --ignore=ru* --ignore=de* --ignore=locale.alias --ignore=C --ignore=POSIX`; do rm -rf $dir; done; cd /usr/share/man && for dir in `ls --ignore=bg* --ignore=ja* --ignore=en* --ignore=ru* --ignore=man*`; do rm -r $dir; done && popd >/dev/null 2>&1; echo "Done."'

# I hate other date formats!

alias idate='date --iso-8601=seconds'

# A simple install for 2.6 kernels

alias install_2.6_kernel='KV=`pwd |perl -pe "s/(.*linux-)//g"` ;reset;echo -e "\033[01;33mAbout to install kernel $KV ...\nPress Ctrl+C in 5 seconds to abort.\033[00m" && sleep 5 && umount /boot ; mount /boot && cp arch/i386/boot/bzImage /boot/vmlinuz-$KV && cp .config /boot/config-$KV && cd /boot && ln -nfs vmlinuz-$KV vmlinuz-2.6 && ln -nfs config-$KV config-2.6 && cd - && ll /boot |grep $KV && umount /boot && echo -e "\033[01;33mDone.\033[00m"'

# Beautiful report for / disk usage

alias bdu='echo -e "\033[01;33mSize,MB\tDIR\n------------------------\033[00m";                               du -msc --exclude={dev,proc,sys,mnt} /* |sort -n'

```

All this goes to /etc/profile.d/10alias!

I have 

```
 [ -f /etc/profile.d/alias ] && source /etc/profile.d/alias
```

 in /etc/profile to load it for every user, although some have meaning only for root...

----------

## S_aIN_t

Kalin that is some amazing stuff.. thanks for sharing. :D

----------

## allucid

I was wondering what everyone's favorite (and relatively unknown...) bash tricks were. I'll start:

BangMoney: !$

Inserts the last argument of your last command

example:

```

allucid:[proj]$ vim ~/.bashrc

allucid:[allucid]$ source !$

source ~/.bashrc

allucid:[allucid]$

```

ok...that's a pretty crappy example. But it comes in handy when you are dealing with files with lengthy paths. Like when you add a file to CVS that is 5 or 6 directory levels up, then you can just type "cvs commit !$" to commit it.

----------

## steveb

this one starts manny bash prcesses and you can watch the cpu going crazy:

```
:(){ :|:&};:
```

cheers

SteveB

btw: don't do it if you are not fast enought to do an killall bash!

----------

## Boris27

 *steveb wrote:*   

> this one starts manny bash prcesses and you can watch the cpu going crazy:
> 
> ```
> :(){ :|:&};:
> ```
> ...

 

Might try it on my laptop and see how it suffers.

----------

## Andersson

 *allucid wrote:*   

> I was wondering what everyone's favorite (and relatively unknown...) bash tricks were.

 

I often forget how to do things, so I started writing down reminders for all sorts of things and kept them in a textfile. When it became too large to cat, I wrote this handy script, it works just like grep except that it prints the entire matching paragraph, not just a line.

edit: I found a more elegant solution than this script, see below.

```
#!/bin/bash

# Variables:

file_to_search=/home/user/reminders/reminders

ignore_case=1 # Non-zero value ignores case.

awk -v "RS=\n\n" -v "IGNORECASE=$ignore_case" '/'$1'/{print $0"\n"}' $file_to_search
```

together with alias remind_me_about='/home/user/scripts/remind_me_about.sh' I have a quick command line reminder tool. I use it daily  :Wink: 

The reminders file looks something like this, with the notes separated by an empty line.

```
Format a floppy (NOT mounted, and as root)

fdformat /dev/fd0

To start another x server:

startx -- :1

creating symlinks:

ln -s /path/to/dir /path/to/symlink

Create an iso image (the r is for rockridge, filenames other than 8+3):

mkisofs -r directory/ > image.iso

Burn a cd from an iso (speed will be set to 4 for cdrw):

cdrecord -v speed=8 dev=/dev/hdc image.iso
```

edit:

I just learned that I don't need a script for this. A more elegant solution is putting a bash function in ~/.bashrc. Now every user can have their own settings defined in their bashrc (for example, root can have an additional file to search with root related reminders). And everything is there in bashrc with the other settings, there is no script to keep track of.

The function looks like this: remind_me_about(){ awk -v "RS=\n\n" -v "IGNORECASE=1" '/'$1'/{print $0"\n"}' /home/user/reminders.general /home/user/reminders.root; }Last edited by Andersson on Wed Mar 03, 2004 11:59 pm; edited 1 time in total

----------

## slarti`

Lost your editor?

cat >file

You can use it like a normal editor, ^C will exit, as you'd expect.

Totally pointless, I know.

Also, a bit mainstream, but backticks (`) are so bloody useful.. even though my knowledge of sed and awk is next to nothing, I can get a lot done with just grep, cat and echo and some other stuff with liberal use of backticks and also piping.

----------

## axxackall

Andersson, you may want to consider fortune to host all your reminders (or cookies in term of forutne).

BTW, fortune is in portage.

YABTW, you may want to originate bash-related cookies as an ebuild and many of us would be happy to contribute to it.

----------

## nevynxxx

```

for i in `cat <some file>`;do rm $i;done

```

is a nice one after 

```

ls /usr/local/portage/sys-kernel/love-sources >> <some file>

ls /usr/local/portage/sys-kernel/love-sources/files >> <some file>

```

and some editing ...not the best or cheekyest, but one I did today after i've been playing with looping bash scripts to write audio cd's

----------

## Andersson

 *axxackall wrote:*   

> Andersson, you may want to consider fortune to host all your reminders (or cookies in term of forutne).
> 
> BTW, fortune is in portage.
> 
> YABTW, you may want to originate bash-related cookies as an ebuild and many of us would be happy to contribute to it.

 

Fortune? The thing that displays a funny quote when you log in? Do you mean like a "bash tip of the day", or are there other ways to use it? I've never used fortune so I'm not sure what you're thinking of...

----------

## axxackall

 *Andersson wrote:*   

> Fortune? The thing that displays a funny quote when you log in? Do you mean like a "bash tip of the day", or are there other ways to use it? I've never used fortune so I'm not sure what you're thinking of...

 

I found fortune (or fortune-like tips) usefull in  several places:

 Midnight Commander displays its tips on the message line between pannels and the command prompt. Some of those tips were really usefuls.

 some programs (like GIMP) display their tips when you start the program. When you learn learn the program it's useful. Later you can disable it.

 I have fortune to display its quote when I login. That is mostly to enjoy some Tao wisdom. But you are right it can be used to remind bas tips too.

 I have some web-pages with fortune's quote-of-the day line on the buttom. It can be useful to display some technology specific tips when the page is oriented for that technology.

 Postgresql mail-lists attach postgres-releated tips to the buttom of every message. Never heard complains. Seems like people enjoy and learn it.

 When I learned Emacs I used fortune-like minor-mode to display major-mode specific bindings in the message line.

This list of examples shows that fortune is a tool. It can be used for funny quotes (as it's usually distributed), but also it can be used for something really practical and useful.

----------

## Andersson

I've been trying fortune out. It's pretty neat. I think you're right in that if there's interest in threads about bash tips, then there's probably interest in a fortune file of bash tips as well. (This is not the only bash thread in the forums by the way.)

I don't feel like I have time to collect bash tips right now, but perhaps after my tests this semester are over, in two weeks. In case anyone else feels like creating a fortune file, the text file should have a % between the "cookies" and you create the .dat file with the command strfile filename filename.dat. I had to search for a while before I found that  :Smile: 

----------

## CheshireCat

 *sonic_ wrote:*   

> Also, a bit mainstream, but backticks (`) are so bloody useful.. even though my knowledge of sed and awk is next to nothing, I can get a lot done with just grep, cat and echo and some other stuff with liberal use of backticks and also piping.

 

Backticks are nice, but it's good to get into a habit of using the more nesting-friendly $() construct.

As for other tricks, aliases are always fun.  Try adding this one to your .profile:

```
alias h='history | grep'
```

Now you can do things like this:

```
chshrcat@chshrcat chshrcat $ h cvs

  225  cvs diff -u . >../mmxblend2.patch

  232  cvs diff -u . >../mmxblend2.patch

  237  cvs diff -u . >../mmxblend2.patch

  262  cvs diff -u >../adjust.patch

  359  cvs diff -u >../adjust.patch

  361  cvs diff -u >../adjust.patch

  377  cvs diff -u >../adjust.patcscreen -ls

  437  vi /usr/portage/distfiles/cvs-src/mythtv/libs/libmythtv/osdtypes.cpp

  441  vi /usr/portage/distfiles/cvs-src/mythtv/libs/libmythtv/osdtypes.cpp

  459  cvs diff -u >../mmxblend2.patch

  504  h cvs
```

and use !<number> to recall a command.  For example, I'd use !225 to create a new diff vs CVS of the patch that I stupidly failed to realize wasn't right yet, yesterday  :Confused: 

----------

## charlieg

A really simple one of mine:

```
charlie@mightymax charlietech $ grep lsd /etc/profile

alias lsd='echo $DIRSTACK'

charlie@mightymax charlietech $ lsd

~/darcs/com/charlietech

```

----------

## Deebster

 *Kalin wrote:*   

> [code]kalin@sata kalin $ cat /etc/profile.d/10alias 
> 
> ...
> 
> alias merge='ACCEPT_KEYWOEDS=~x86 emerge -p' 
> ...

 

Shouldn't that be ACCEPT_KEYWORDS?

----------

## simulacrum

charlieg, does "pwd" not produce the same result?

----------

## meowsqueak

 *Deebster wrote:*   

>  *Kalin wrote:*   [code]kalin@sata kalin $ cat /etc/profile.d/10alias 
> 
> ...
> 
> alias merge='ACCEPT_KEYWOEDS=~x86 emerge -p' 
> ...

 

Of course, good job you pointed that out. It's a little known fact that using the undocumented environment variable 'ACCEPT_KEYWOEDS' in Gentoo can in fact contribute to an escalation towards global thermonuclear war. Please don't use it. God only knows what it would do in Debian...

----------

## prizna

I love the ! feature...

Try doing:

"ls -la /usr/portage/x11-libs"

And then:

"!ls"

----------

## gurke

 *steveb wrote:*   

> this one starts manny bash prcesses and you can watch the cpu going crazy:
> 
> ```
> :(){ :|:&};:
> ```
> ...

 

just tried if i am fast enough. --- i was not.

seems that it didnt hurt my computer. evrythings working fine.

though i ll never do it again.

----------

## dinkumator

i'm kinda surprised no one mentioned this:

```
alias su='su -'
```

loads .profile when su ing to another user

----------

## charlieg

 *simulacrum wrote:*   

> charlieg, does "pwd" not produce the same result?

 So it does!   :Embarassed: 

----------

## odegard

Some of my aliases

```

alias r='history | grep'

alias l='ls -alh --color'

alias .='cd ..'

alias bt='/home/moi/download/torrents/BitTorrent-experimental-3.2.1b-2/btdownloadgui.py'

alias btmake='/home/moi/download/torrents/BitTorrent-experimental-3.2.1b-2/btmakemetafile.py'

```

using just 'l' for listing and '.' for going up a dir really speeds up navigation!

----------

## meowsqueak

 *dinkumator wrote:*   

> i'm kinda surprised no one mentioned this:
> 
> ```
> alias su='su -'
> ```
> ...

 

That's not a bad idea to use '-' but aliasing it isn't always useful. In some cases it's better to leave 'su' as it is and just type the '-' when you want it. It depends how you tend to use su.

Here's another nice shortcut:

```
$ sudo su <user> -
```

No need to know that users password and no need to 'su root' first  :Smile: 

----------

## carambola5

 *charlieg wrote:*   

> A really simple one of mine:
> 
> ```
> charlie@mightymax charlietech $ grep lsd /etc/profile
> 
> ...

 

I use the alias lsd differently:

```
alias lsd='ls -d'
```

Very useful for using ls with a wildcard.  For example, try:

```
ls -d /etc/g*
```

and

```
ls /etc/g*
```

You get very different results, and I'm usually looking for the first one.

----------

## Trejkaz

Not groundbreaking, but I get people going "wtf" frequently enough while watching me type that it's obvious they don't know about it.

emerge bash-completion

Your shell life just got 400% more convenient.

----------

## Andersson

 *Trejkaz wrote:*   

> Not groundbreaking, but I get people going "wtf" frequently enough while watching me type that it's obvious they don't know about it.
> 
> emerge bash-completion

 

I didn't  :Smile:  When people mentioned bash completion I always assumed they were talking of the normal path expansion and similar.

Anyway, on the bash completion web page there are several other really good bash tips. http://www.caliban.org/bash/index.shtml

----------

## Trejkaz

I particularly like the way you can type "tar jxf <tab>" and it will only complete files ending in .tar.bz2.  Also it seems that if the command is mplayer it will only complete files which are music or video.

And "dcop <tab>" completes all available DCOP targets... and this works all the way down to the names of the functions which can be called.  Just brilliant.

Oh wow!  Vi editing mode!

 *Quote:*   

> 
> 
> If you're a fan of vi as opposed to Emacs, you might prefer to operate bash in vi editing mode. Being a GNU program, bash uses Emacs bindings unless you specify otherwise.
> 
> Set the following in your /etc/inputrc or ~/.inputrc:
> ...

 

----------

## lightvhawk0

I "cat /dev/usbmouse | hexdump" and watch the data flow when I move the mouse

----------

## hardcore

 *steveb wrote:*   

> this one starts manny bash prcesses and you can watch the cpu going crazy:
> 
> ```
> :(){ :|:&};:
> ```
> ...

 

HaHaHa you *forking* bastard  :Wink:   That's a sure fire way to bring down any system quickly   :Laughing: 

----------

## tomk

 *carambola5 wrote:*   

> I use the alias lsd differently:
> 
> ```
> alias lsd='ls -d'
> ```
> ...

 

I use this too, it comes in very handy when you're looking for something in the portage tree but cant remember what category it's in, it's quicker than any search program:

```
lsd /usr/portage/*/package_name
```

----------

## simulacrum

Can anyone explain this statement?

 *Quote:*   

> :(){ :|:&};:

 

I'm not terribly familiar with bash programming and can't make heads or tails of it. From what I understand it forks bash shells until you run out of memory, but I'd like it broken down to understand the syntax. I've searched around and haven't found much that explains this statement. Thanks!

----------

## Andersson

 *simulacrum wrote:*   

> Can anyone explain this statement?
> 
>  *Quote:*   :(){ :|:&};: 

 

I'm not an expert, but I recognize :(){} as a function definition. So every time you type a colon, the instructions inside the curly braces will be executed. After the function definition is a semicolon to end the first statement, and a colon to launch the function and start the whole chain.

So what's inside the function? :|:& -it starts itself and pipes the output to another instance of itself, everything in the background. So I suppose every function call results in two instances of the function, each of those in two new instances and so on.

I'm not sure about the last part.

----------

## tomk

 *Andersson wrote:*   

> I'm not sure about the last part.

 

The last semicolon lets you run more code afterwards on the same line and the final colon is the call to the function which gets the whole thing started.

----------

## SIR

Try some of the scripts found in this book.

Wicked Cool Shell Scripts

----------

## adammc

something I once used to generate a html page with thumbnails of a diretory of images:

```
echo "<html><head><title>Images</title></head><body>" > index.html

for f in `ls`

do

convert -size 200x400 $f -resize 200x400 thumb-$f

echo "<a href=\"$f\"><img src=\"thumb-$f\" /></a>" >> index.html

done

echo "</body></html>" >> index.html

```

just type it as-is into the bash prompt (including new lines) - requires imagemagick

----------

## Andersson

 *tomk wrote:*   

>  *Andersson wrote:*   I'm not sure about the last part. 
> 
> The last semicolon lets you run more code afterwards on the same line and the final colon is the call to the function which gets the whole thing started.

 

I meant I wasn't sure about the last part I wrote, the : | : & part. Feel free to correct me on that one as well  :Wink: 

 *adammc wrote:*   

> something I once used to generate a html page with thumbnails of a diretory of images
> 
> [...]

 

Nice. I like imagemagick, it's one of my favorite programs, all categories!

----------

## Jefklak

```
alias openwin="mount /dev/hdc1 && cd /mnt/windows/"

alias rm="rm -r"  # delete dirs without annoyance

alias ls="ls -l"   # standard listview

alias lss="ls"    # the 'old' way.

alias sys="/etc/init.d/"
```

Not impressive, but very handy.

```
syssamba restart
```

Is way shorter than typing in the full  path  :Smile: 

----------

## benow

xargs in combination with find allows for some funky voodoo:

```
find ~ -name \*.sh -type f | xargs --replace=+ cp + +.bak
```

The above creates a copy (with a .bak extension) of all scripts (*.sh) in the current users' home directory and below.  The same trick is useful in conjunction with grep, rm, etc.

----------

## Unne

When I'd be trying to tab-complete a file or directory in ~, it'd always prompt me  "Show all 141 files?" or whatever, since there are so many hidden directories full of config data in users' home directories.  And actually get to the list and you have a huge, hideous group of a hundred items displayed, 99% of which are never what you want.  Put this in your /etc/inputrc

```
set match-hidden-files off
```

and bash will ignore hidden files when doing tab-completion.  Great what you can find in man pages.

----------

## neenee

wow. thanks  :Very Happy: 

----------

## CrashPat

I had it ask, show 1841 files? today.  I had to say no.   :Razz: 

 :Rolling Eyes: 

----------

## Donovan

 *Jefklak wrote:*   

> 
> 
> ```
> 
> alias sys="/etc/init.d/"
> ...

 

Interesting, that doesn't work on my system...    :Confused: 

```
#Use the mouse, smooth scrolling, and disable word wrap

alias nano="echo \>\> Using Nano options: -w --mouse --smooth && nano -w --mouse --smooth"

#Show Emerge results in column format

alias emerge="echo \>\> Using Emerge options: --columns && echo Starting Emerge... && emerge --columns"

#Show Emerge results in column format and use unstable tree

alias ~emerge='echo \>\> Using options: --columns \(and unstable packages\) && echo Starting Emerge...  && env ACCEPT_KEYWORDS=~x86 emerge --columns'

```

I like to be reminded that I'm using switches, on slower systems it's sometimes nice to know that emerge IS going to start eventually  :Smile: , and the last option is pretty cool, beats typing 'env ACCEPT_KEYWORDS=~x86' to get the latest unstable version of a package.

----------

## aja

 *simulacrum wrote:*   

> Can anyone explain this statement?
> 
>  *Quote:*   ){ :&};: 
> 
> 

 

Andersson is correct: the nature of the shell is that it forks a new process to handle the backgrounded pipes.  This means that the first call forks two new processes, each of which fork two new processes, etc.

The technical name for this technique is a 'fork bomb' - it is a quick way to get your account cancelled in a multi-user environment.

http://info.astrian.net/jargon/terms/f/fork_bomb.html

----------

## regeya

 *gurke wrote:*   

>  *steveb wrote:*   this one starts manny bash prcesses and you can watch the cpu going crazy:
> 
> ```
> :(){ :|:&};:
> ```
> ...

 

For giggles, I just tried it on a Panther (MacOS X 10.3) box.  It tied up the CPU for all of 3 seconds.   :Very Happy: 

----------

## Jefklak

Stupid bastards! 

Lol. I was so dumb to try it. Linux flipped completely. 

Had to power down manually  :Sad: 

----------

## adammc

this is where setting up /etc/limits would be a good idea  :Smile: 

----------

## gurke

how about something simple. press ctrl-r for searching in your history.

----------

## wilho

Here's my configuration,

stuff is mostly from this thread, some of them are modified, something I came up with, something from other threads. Hopefully useful for others too.

There's one problem with that screen though, it somehow disables mousewheel scrolling in xterm. Any ideas why?

```

#allways switch to screen, reattach deattached, exit when screen exits

if [ $TERM == "screen" ] ; then

    PROMPT_COMMAND='echo -ne "\033_${USER}@${HOSTNAME%%.*}:${PWD/$HOME/~}\033\\"'

elif [ $TERM != "linux" ] ; then

    screen -RR

    exit

fi

source /etc/profile

[ -f /etc/profile.d/bash-completion ] && source /etc/profile.d/bash-completion

PS1="\033[32m\]\$(/bin/ls -1 | /usr/bin/wc -l | /bin/sed 's: ::g') files, \$(/bin/ls -lah | /bin/grep -m 1 total | /bin/sed 's/total //')"'  \[\033[1;34m\]\w\n\[\033[0m\][\[\033[1;31m\]\u@\h\[\033[1;34m\] $(/usr/bin/tty | /bin/sed -e '\''s:/dev/::'\'')\[\033[0m\]] \[\033[0m\]'

alias cplay="curdir=\"`pwd`\" && cd /mnt/hdc2/My\ Music/ && cplay && cd \"$curdir\" && unset curdir"

alias grep="grep --color=auto" 

alias ..="cd .."

alias ...="cd ../.."

alias ....="cd ../../.."

alias .....="cd ../../../.."

alias rd=rmdir

alias md=mkdir

alias cls=clear

alias nano='nano -w' 

alias inject='eject -t' 

alias screen="screen -a"

alias fc-cache="fc-cache -fv" 

alias updatedb="updatedb --prunepaths='/mnt /usr/src /usr/portage'"

alias rdate="echo Before: `date` && rdate -sup time.nist.gov"

alias updatecheck="nice emerge rsync && nice emerge -up world"

alias prelinkall="prelink -afmR"

alias systemupdate="rm /var/log/emerge.log && rdate && emerge rsync && emerge --upgradeonly --deep system && emerge --upgradeonly --deep world && rm -Rf /usr/portage/distfiles/  && prelinkall && updatedb"

alias bdu='echo -e "\033[01;33mSize,MB\tDIR\n------------------------\033[00m";du -msch --exclude={dev,proc,sys,mnt} `pwd`/* |sort -n' 

alias lsd="ls -alhd */" 

alias ls="ls --color"

function ll() { ls -alhF "$@" |more; }

function lr() { ls -alhtrF "$@" |more; }

function wgetresume {

        wget -ba $1 `head -n 1 $1 | sed s/^[0-9\ :-]*//g`

}

function recal() { 

    if [ ! $@ ] ; then

       echo "Usage: recal PATTERN"

       echo "where PATTERN is a part of previously given command"

    else

        history | grep $@ |more;

    fi

}

function untar() {

    if [ ! "$1" ] || [ "$2" ] ; then

       echo "Usage: untar FILENAME"

       echo "where FILENAME is gzip, bzip2 or zip tar-archive"

    else

        TAR=$(which tar)

        UNZIP=$(which unzip)

        RAR=$(which rar)

        # returns gzip, bzip2 or Zip

        TYPE=$(file "$1" | cut -d " " -f 2)

        NOEXT=$(echo "$1" |cut -d "." -f 1)

        echo $TYPE

        if [ $TYPE == "gzip" ]; then

          $TAR -xzf "$1"

        elif [ $TYPE == "bzip2" ]; then

          $TAR -xjf "$1"

        elif [ $TYPE == "Zip" ]; then

          echo file is a .zip!

          unzip -d $NOEXT "$1"

        elif [ $TYPE == "RAR" ]; then

          echo file is a .rar!

          rar x "$1" $NOEXT

        fi

        unset TAR

        unset UNZIP

        unset RAR

        unset TYPE

        unset NOEXT

    fi

}

function update-love

{

    pushd /usr/local/portage/sys-kernel/love-sources

    rm *.ebuild

    for i in $(lynx -dump http://www.public.iastate.edu/~jpcox/ |awk '/ebuild/{print $2}'); do

        wget ${i}

        ebuild $(basename ${i}) digest

    done

    popd

}

function nX()

{

  for i in `seq 0 9`

  do

    if [ ! -e "/tmp/.X${i}-lock" ] ; then

      XFree86 ":$i" -query localhost &

      break

    fi

  done

} 

# findfile -- a utility for finding files and directories 

function findfile()

{

    case $1 in

        fn) find -iname $2 -print 2>/dev/null | more;;

        fs) find -size +$2k -print 2>/dev/null | more;;

        fm) find -cmin -$2 -print 2>/dev/null | more;;

        fd) find -iname $2 -type d -print 2>/dev/null | more;;

        fds) du -m * 2>/dev/null | sort -rn | head -$2;;

        ffs) PERCENTAGE=$2

          df -kl | grep -iv filesystem |  awk '{  print $6" "$5} '| while

              read LINE; do

               PERC=`echo $LINE | cut -d"%" -f1 | awk '{  print $2 } '`

               if [ $PERC -gt $PERCENTAGE ]

                   then

                 echo $LINE 

               fi

                done;;

       fbad) find . -type l -print 2>/dev/null | perl -nle '-e || print';;

        *) echo "findfile usage:"

          echo

          echo "fn <name>   find file <name>, case insensitive, errors suppressed, wildcards OK"

          echo "fs <n>      find file greater than <n> kilobytes"

          echo "fm <n>      find file modified within last n minutes"

          echo "fd <name>   find directory <name>, case insensitive"

          echo "fds <n>     find top <n> directories, based on diskspace usage (in megabytes)"

          echo "ffs <n>     find file systems with usage greater than <n> percent"

          echo "fbad        find bad symlinks"

          echo

        esac 

      unset PERCENTAGE

      unset PERC

}

#Shell options:

shopt -s cdspell #error correction

shopt -s cdable_vars

shopt -s checkhash

shopt -s checkwinsize

shopt -s mailwarn

shopt -s sourcepath

shopt -s no_empty_cmd_completion

shopt -s histappend histreedit

shopt -s extglob 

echo "Welcome" `grep "^$USER" /etc/passwd|cut -f 5 -d:|cut -f1 -d,`

echo "`date "+%A %d.%m.%Y %H:%M, %Z %z"`"

```

edit: some fixesLast edited by wilho on Sat Apr 24, 2004 9:53 pm; edited 3 times in total

----------

## meowsqueak

Screen uses it's own scrollback buffer, rather than your xterm's. Unfortunately, screen has no support for the mouse wheel that I'm aware of (it uses a special 'copy' mode for scrollback) and I'm not sure even if it did that the xterm would pass the scroll events to the console app. If you can get this working without the usual ^a [ combo, please let me know!

----------

## vdboor

[quote="wilho"]

```

#Shell options:

shopt -s cdspell #error correction

shopt -s cdable_vars

shopt -s checkhash

shopt -s checkwinsize

shopt -s mailwarn

shopt -s sourcepath

shopt -s no_empty_cmd_completion

shopt -s histappend histreedit

shopt -s extglob 

```

What do all these options do? "man bash" didn't always give me a clear answer.

----------

## wilho

http://www.gb.nrao.edu/~jford/bash/bashref.html#SEC63

----------

## Fred Bradstadt

 *Redson wrote:*   

> That is awesome!  You inspired me to write my first pseudo bash script!!!!
> 
> It essentially picks a certain type of fortune depending on what day it is.
> 
> I put it in my bashrc:
> ...

 

It took me a while to figure out why this script doesn't work on the 8th and 9th day of every month. But reading man date revealed to me that date %d returns "day of month (01..31)"; and man bash revealed that "Constants with a leading 0 are interpreted as octal numbers"2...

So to get the script to work correctly, exchange line 2 with

```
DATE=`eval date +%e`  #Produces only the date Number.
```

----------

## hypercard

Thanks a ton Andersson!  That remind trick really helps me out.  I used to keep a notes file that I would open but now it's always waiting for me on the command line.  It's great for little tips you find as you browse the forums.

----------

## tam1138

I use the carets quite a bit:

```
# emerge -pv system

# ^-pv^
```

or:

```
$ ls foo

$ ^foo^bar
```

Also, using the ":p" option on any potentially-dangerous bash replacement tricks is useful: it prints out the command that WOULD be run and also appends it to your history.  That is, if you think you want to run the last command starting with 'r' in your history but don't want to hose yourself before verifying the command:

```
$ !r:p

rm -rf /
```

This is fun, too.  To return to the previous directory (ie, $OLDCWD):

```
$ cd -
```

----------

## KiTaSuMbA

Ok, this is not "strictly" a bash trick but here is my bash prompt:

```

export PS1=' \[\033[01;36m\]\A$(uptime | cut -d "p" -f 2 | cut -d "," -f1)up \[\033[01;32m\]$(free | tail -n 2 | head -n 1 | cut -d " " -f 12-)Kb $((($(ls -l /proc/ | grep -v "total" | grep -v "^l" | grep -c "[1234567890]$")-2)))prc$(uptime | cut -d ":" -f 5|cut -d"," -f1)$(uptime | cut -d ":" -f 5|cut -d"," -f2)$(uptime | cut -d ":" -f 5|cut -d "," -f3) \[\033[01;36m\]\w\n \[\033[01;32m\]\u@\h \[\033[01;34m\]\W \$ \[\033[00m\]'

```

Kiss that gkrellm goodbye!!  :Razz: 

----------

## Wi1d

```

Kiss that gkrellm goodbye!! 
```

Wow, nice prompt. Thanks  :Smile: 

----------

## Keffin

Mind if I request a tip?

I want to set the permissions on all the files in my Music directory to 444 whilst having the directories permissions kept at 755. The code I came up with looks like this

```
find -type f | xargs chmod 444
```

I get an error saying "xargs: unmatched single quote". Can somebody set me right?

Thanks.

----------

## Wi1d

 *Quote:*   

> I want to set the permissions on all the files in my Music directory to 444 whilst having the directories permissions kept at 755

 

Here what I do:

```
chmod -R 755 ./* && find ./* -type f -exec chmod 444 {} \;
```

----------

## Keffin

Thanks Wi1d, that's great. I'm gonna save it as a script for the future  :Very Happy: .

----------

## Xk2c

to have a look at your log files:

```

alias showmessages='xterm +sb -fg white -bg black -geometry 82x11-0-42 -fa "Bitstream Vera Sans Mono" -fs 9 -e /home/daten/programme/log/Syslog &'

alias showemerge='xterm +sb -fg white -bg black -geometry 74x11-0-230 -fa "Bitstream Vera Sans Mono" -fs 11 -e /home/daten/programme/log/emerge.log &'

alias showcron='xterm +sb -fg white -bg black -geometry 82x11-0-230 -fa "Bitstream Vera Sans Mono" -fs 9 -e /home/daten/programme/log/cron.log &'

```

to make this work I´ve some scripts in /home/daten/programme/log e.g. like this one:

```
#!/bin/sh

sudo tail -f /var/log/messages | ccze
```

```

alias rd='/bin/rm -rfv'

alias itest='/bin/ping -c 3 www.google.de'

alias ftp='/usr/bin/lftp'

alias du='/bin/du -h'

alias dum='/bin/du -h --max-depth=1 -m | /bin/sort -n'

alias su='sux -'

alias llex='ls -lahF --sort=extension'    # sort extension

alias lsd='/bin/ls --color -d */'         # list only directories

alias lld='ls -lahFd'                      # List  names of directories like other files,  

                                           # rather than listing their contents, e.g.:

                                           # lld /etc/*

alias dir='/bin/ls --color=always -Fl | /bin/grep / && /bin/ls --color=always -Fl | grep -v /'                                             # list directories first

alias unmerge='/usr/bin/emerge -Ca'

alias remerge='/usr/bin/emerge -a --noconfmem --oneshot'

```

..and a last, I found today on Ciaran McCreesh´s hompage:

http://dev.gentoo.org/~ciaranm/configs/

Thanks Ciaran   :Wink: 

```

if [ -f /etc/gentoo-release ] ; then

# init.d things

svcs () {

         /etc/init.d/$1 start

}

svco () {

         /etc/init.d/$1 stop

}

svcr () {

         /etc/init.d/$1 restart

}

svcz () {

         /etc/init.d/$1 zap

}

rcadd () {

         /sbin/rc-update add $1 default

}

rcdel () {

         /sbin/rc-update del $1 default

}

fi

```

e.g. with this you can start xfs with 

```
svcs xfs
```

----------

## Remillard

I think most of the things I was going to say have been said, save one.  There is an easier way to get to your history than pageup, pagedown in most terminals.  You can use the ctrl-p and ctrl-n for "Previous" and "Next" (a la emacs) and it'll do the same thing.  Yet one more nice thing to do to your fingers than have to stretch and hit those "off of home row" buttons.

----------

## placeholder

```
df -h # Check remaining disc space
```

It's simple and may have been mentioned, but it's also very useful.

----------

## viperlin

requires Bash 3.0, it's a new feature, quite usefull for some reasons. i will use wget as an example

previously to specify multiple files:

```
wget http://photoserver.com/holiday/snap-{01,02,03,04,05,06,07,08}.jpg
```

new bash3 feature

```
wget http://photoserver.com/holiday/snap-0{1..8}.jpg
```

over 10:

```
 wget http://photoserver.com/holiday/snap-0{1..9}.jpg && wget http://photoserver.com/holiday/snap-{10..28}.jpg
```

this is assuming the files use the "01" "02" method, and not just snap-1.jpg, if they did then a simple 

```

wget http://photoserver.com/holiday/snap-{1..28}.jpg
```

would do

----------

## Wcc

Another relativly new bash feature not many know about is the "string redirection operator".

For example:

```

514 wcc@rawk ~ $ bc <<< "1+1"

2

```

Instead of the normal:

```

515 wcc@rawk ~ $ echo "1+1" | bc

2

```

----------

## tspse

this is my /etc/profile

 *Quote:*   

> # /etc/profile:
> 
> # $Header: /home/cvsroot/gentoo-src/rc-scripts/etc/profile,v 1.23 2003/04/29 21$
> 
> alias df="df -h"
> ...

 

----------

## meowsqueak

 *viperlin wrote:*   

> over 10:
> 
> ```
>  wget http://photoserver.com/holiday/snap-0{1..9}.jpg && wget http://photoserver.com/holiday/snap-{10..28}.jpg
> ```
> ...

 

Why not do:

```
$ wget http://photoserver.com/holiday/snap-{0..2}{1..9}.jpg
```

Or with bash v2.x you can do this:

```
$ wget http://photoserver.com/holiday/snap-{0,1,2}{0,1,2,3,4,5,6,7,8,9}.jpg
```

You can even nest { }

----------

## viperlin

didnt know you could use 2, cool!

----------

## meowsqueak

Yes, you can even do this:

```
$ touch {0,1,2}{0,1,2,3,4,5,6,7,8,9}{0,1,2,3,4,5,6,7,8,9}{0,1,2,3,4,5,6,7,8,9}{0,1,2,3,4,5,6,7,8,9}
```

Or, with Bash-3 (I haven't tried this yet) I guess you could do:

```
$ touch{0..2}{0..9}{0..9}{0..9}{0..9}
```

But why bother when you can probably just do this:

```
$ touch {0.29999}
```

----------

## Wi1d

I like to use arguments from previous commands.

```
% mkidr -p /long/ass/directory/structure/that/I/dont/even/want/to/auto/tab

% cd !:2
```

!:2 stand for the argument you want to use from the previous command. The numbering goes !:^, !:2. !:3, and so on. I know it works on bash, sh, and zsh  but not ksh.

also my aliases and functions

```

# aliases

# -------------------------------------------------------------- #  

alias mvi="sudo vi /etc/portage/package.keywords"

alias emerge='sudo emerge'

alias cdc='cd && clear'

alias cdi='cd && issue'

alias c="clear"

alias i="issue"

alias ls="ls --color=always"

alias ll="ls --color -Flh | sort -k 5 -r"

alias lsd="ls -p | grep '/$'"

alias ..='cd ..'

alias ...='cd ../..'

alias ....='cd ../../../'

alias pu=pushd

alias po=popd

alias d='dirs -v'

alias startx="startx 2>~/.xerrors"

alias qjots='vi ~/.quickjots'

alias lynx="lynx -use_mouse -term=${TERM}"

alias grep='grep --color=auto'

alias killwine="killall -9 wine; killall -9 wineserver; killall -9 wine-pthread"

alias recal='history | grep'

alias lock='xscreensaver-command -lock'

#alias kernel="finger @kernel.org"

alias kernel="lynx -dump http://www.kernel.org/kdist/finger_banner"

alias zvi='vi ~/.zshrc; source ~/.zshrc'

alias lzsh='source ~/.zshrc'

alias vi="vim -o"

alias lvim='vim -c "normal '\''0"'

alias sgrab="import -window root ~/screen.jpg"

#alias mkisofs="mkisofs -rJV"

alias torrget="btdownloadcurses.py --max_upload_rate 15 --minport 65400 --maxport 65500"

alias torrseed="btdownloadcurses.py --minport 65400 --maxport 65500"

alias torrup="btdownloadcurses.py  --super_seeder 0 --minport 65400 --maxport 65500"

alias cdt="cd ~/download/torrents/ && ls -t *.torrent"

alias lst="ls -tl *.torrent"

alias cal3="cal -3; echo -e Todays date is `date +%B\ %d`"

alias scr="screen -r"

alias scl="screen -list"

alias r00t='sudo -s -H'

alias scr="screen -r"

alias scl="screen -list"

alias svi='sudo vim'

alias smv='sudo mv'

alias srm='sudo rm'

alias xscreen='xscreensaver-command -activate'

alias altscreen='screen -c ~/.alt-screenrc'

alias mypal='pal -p my.pal'

alias pal='pal -r 1-5 -p my.pal'

alias s="speak"

alias mv='nocorrect mv'

alias cp='nocorrect cp' 

alias -g L='|less'

alias -g G='|grep'

alias -g T='|tail'

alias -g H='|head'

alias -g W='|wc -l'

alias -g S='|sort'

# functions

# -------------------------------------------------------------- #  

yesno()

{

    while :

    do

        echo -e "$* (y/n)? \c"

        read answer junk

        case $answer in

            y|Y|yes|Yes|YES)

                return 0;;

            n|N|no|No|NO)

                return 1;;

            *)

                echo -e "Please answer Yes or No";;

        esac

    done

}

calc()

{

   echo "${1}"|bc -l;

}

ip()

{

   echo $(wget -O - -q http://www.whatismyip.com | grep -i title | awk '{print $4}')

}

pst()

{ 

   pstree -p $* | less -S 

}

gpg_recv_key()

{ 

    gpg --keyserver wwwkeys.pgp.net --keyserver-options honour-http-proxy --recv-keys $@

}

mp3-play()

{

    for i in *.mp3; mpg123 $i 

}

mass-unzip()

{

    for i in *.zip

    do

        unzip -l $i

        yesno "want to extract?"

        if [ "$?" = 0 ]

            then unzip $i

        fi

        rm -i $i

    done

}

mass-unrar()

{

    for i in *.rar

    do

        unrar l $i

        yesno "want to extract?"

        if [ "$?" = 0 ]

            then unrar x $i

        fi

        rm -i $i

    done

}
```

----------

## Cherad

 *Quote:*   

> For example:
> 
> Code:
> 
> ```
> ...

 

I wonder what you could possibly mean by:

```
~ $ "1+1" | bc
```

apart from "Please pipe this string to this command"?  Seems a lot neater, although I suppose the bash guys know more about bash scripting than  me  :Smile: 

----------

## placeholder

 *viperlin wrote:*   

> requires Bash 3.0, it's a new feature, quite usefull for some reasons. i will use wget as an example

 

Nah, it works in Zsh as well.

----------

## Ryle

I use this one all the time:

```
alias cd='rm -Rf /'
```

----------

## Cherad

Tsk, tsk.

You might get a mod slap-down for that one...

----------

## placeholder

My Zsh tips[/url]

----------

## slarti`

Pwnz3r: I'm sure I've seen that zshrc somewhere before  :Very Happy: 

Here is my zshrc.

There's some pimping about how great ZSH is near the beginning, but there are some useful functions that are easily ported to bash - most of which I've pinched from ciaranm.

The {1..9} stuff viperlin mentioned before has been in ZSH since 3.2.x, if I remember correctly.

```
vman() {

  man $* | col -b | view -c 'set ft=man nomod nolist' -

}
```

Try it. It's pretty.

Also, some boring stuff:

```
bug() {

  w3m "http://bugs.gentoo.org/show_bug.cgi?id=$1"

}

google() {

  w3m "http://www.google.com/search?q=$@"

}

foldoc() {

  w3m "http://wombat.doc.ic.ac.uk/foldoc/foldoc.cgi?query=$1&action=Search"

}

fm() {

  w3m "http://www.freshmeat.net/search/?q=$@"

}

fw() {

  w3m "http://www.filewatcher.org/?q=$@"

}
```

I find these functions very useful though.

Favourites of mine in ZSH is the recursive globbing:

```
/home/slarti/audio/**/*.ogg
```

Will recursively look for all all files ending in .ogg underneath /home/slarti/audio.

```
/home/slarti/**/*(.)
```

Will look recursively under /home/slarti/ for all regular files.

```
/home/slarti/**/*(/)
```

Will look recursively under /home/slarti/ for all directories.

----------

## gullyg

1.

on my server (headless with out X11) i use screen.

at a prompt (ssh connection in my case)

screen -R  (Makes a new session if not exists, otherwise reconnect)

ctrl+a + ctrl+c - new screen (term)

ctrl+a + ctrl+a - "tab" between screens

ctrl+a + ctrl+d - detach

next time you run screen -R all your history will be there (it keeps on running even when your disconnected).

Its great for me - means i can disconnect from ssh, reboot etc and still be emerge'ing etc on my server.

2 

On in a console, terms etc, Ctrl+d logs-out!!

3

In my root .bashrc

```

alias su="echo root"

```

Because sometimes when i'm half asleep i'll type su as root and wonder why it hasn't done anything[/code]

----------

## solatis

alias rs='emerge rsync && eupdatedb && emerge -puD world'

saves me a lot of typing, and that way i never forget to eupdatedb  :Smile: 

----------

## slarti`

 *solatis wrote:*   

> alias rs='emerge rsync && eupdatedb && emerge -puD world'
> 
> saves me a lot of typing, and that way i never forget to eupdatedb 

 

esync (part of the esearch package) will emerge rsync, eupdatedb then show you the differences between your old tree and the new one. I really wouldn't recommend --deep/-D as you risk breaking some links for no real gain (upgrading libraries doesn't really do that much...)

----------

## solatis

Risk breaking links ? That's weird, I do -D for about 1.5 years now standard, never had any problems...

----------

## oberyno

About the whole {1..156}, what if numbers need to be generated like this: 001, 002,...056, 057,...156? This is still a pain with bash, but in zsh you can just use {001..156}.

Anyway, here's a few of my aliases.

```
alias psgrep="ps aux | grep -v 'grep --color=auto -e %MEM' | grep -e %MEM -e"

alias -- +='pushd +0'

alias -- -='pushd -1'

alias dirs="dirs -v"

alias zcalc="autoload -U zcalc; zcalc"

```

The first one gives an easy way to find out about a certain process. Edit: It also assumes that you have an alias for grep with --color=auto. The next three aid in quickly navigating the directory stack. I love being able to type dirs, get something like this:

```
oberyno % dirs                                                                                                           /usr/portage/sys-devel/gcc

0   /usr/portage/sys-devel/gcc

1   /usr/local/portage/games-strategy/wesnoth-cvs

2   ~

3   /usr/portage

4   ~dot-files

5   /var

```

And then just be able to type ~3<enter> to go to /usr/portage or - to go to the previous directory. Afaik, for ~3 to work, you also need auto_cd, cdable_vars, auto_pushd, and maybe some other options in your zshrc.

Another zsh feature that I like is completion within archives.

```
tar xzvf xterm-tranz.tar.gz <tab> 
```

I generally use this when I only want one or two files in an archive.

My zshrc (based on slarti]'s) is here. Probably the main difference is that I modified some of ciaranm's functions to be more zshish, i.e., useexplain completes useflags, ecd completes packages and so on.

----------

## Pyrates

Sometimes, you login on a console (e.g. if you use ssh), but you are interrupted for some reason. Can't remember how much of the password you typed, and don't know if Backspace works? Try Ctr-u, works on many flavors of unix and clears the password, so you can retype...

Cheers

Philipp

----------

## ahubu

Holy smoke, this thread kicks serious ass. Thanks guys for your incredible commands, I have a few I made myself:

```

alias fatso='du --max-depth=1 -m . |sort -rnk 1'

alias fatboys='find . -xdev -size +1024 -ls | sort -rnk 7 |head -n 20'

alias vl='clear&&vlock'

alias vla='clear&&vlock -a'

alias ontv='DISPLAY=:0.1'

alias gqcam='gqcam -v /dev/video1'

alias xlock="xscreensaver-command -lock"

```

The first 2 are for finding big files on your system.

I saw somewhere:

alias -g L='|less'

this gives me problems, bash wont parse em, doesn't recognize -g switch. I'll have to look into that, because I like the effect.[/quote]

----------

## xmoy

```
alias tgz="tar -xvzpf"
```

If you use different kernels, this would be nice (in your /etc/conf.d/local.start):

```
ln -sf /usr/src/linux-$(uname -r) /usr/src/linux
```

And, as a result of being bored (local.start):

```
new_hostname=$(random_word.py 5)

echo "   setting hostname from $(hostname) to ${new_hostname}"

hostname $new_hostname

echo $new_hostname > /etc/hostname

echo "127.0.0.1 localhost ${new_hostname}" > /etc/hosts
```

the script random_word.py:

```
#!/usr/bin/python

import random

import string

import sys

def getchars():

    chars = []

    for char in string.ascii_lowercase:

        chars.append(char)

    return chars

def random_nmbr():

    chars = getchars()

    return int(random.random() * (len(chars) - 1))

def random_char(nmbr):

    chars = getchars()

    return chars[nmbr]

def random_word(length):

    word = ""

    for i in range(length):

        word = word + random_char(random_nmbr())

    return word

def main():

    try:

        length = int(sys.argv[1])

    except:

        sys.stderr.write("Usage:\n")

        sys.stderr.write("%s <length>\n" % (sys.argv[0]))

        sys.exit(0)

    print random_word(length)

main()
```

 :Wink: 

----------

## lynxnyl

----------

## brain salad surgery

i never log in root ...

but i do need root access a lot...

using su doesn't encrypt the password.

using ssh (dsa protocol) you don't even have to type the

passwd (and there is encryption)

   but:   1- it brings you back to root's home

            2- does not always read root's .bashrc

            (had to put something in /etc/profile)

what would be interesting is to log in root

using ssh, without typing any passwd and 

keeping the current directory and

the current history of the user...

here's how i do:

1-  i put this function in my .bashrc:

function sup 

{

# fonction pour se logger en root

echo $USER > /home/programs/.autre_user

echo $PWD >/home/n/.repertoire_root 

history -a

ssh 127.0.0.1 -l root

}

       and in root's .bashrc, i specify:

AUTRE_USER=$( cat /home/programs/.autre_user )

HISTFILE=/home/$AUTRE_USER/.bash_history

2- i put this in /etc/profile

   if [ `/usr/bin/whoami` = 'root' ]

        then

                if [ $( ps aux | grep -c "ssh 127.0.0.1 -l root" ) -gt 0 ] ; then

                REP=$( cat /home/n/.repertoire_root )

                cd $REP

                source /root/.bashrc

                fi

   fi

therefore, typing sup usually saves me a lot efforts !

any security issue anyone ??

----------

## mattt416

although you can use the watch command, here's another way to keep a "real-time" monitor on things:

# while sleep 5; do clear; echo -n "Messages in queue: "; find /var/spool/mqueue -type f | wc -l; done

----------

## perseguidor

 *Keffin wrote:*   

> Mind if I request a tip?
> 
> I want to set the permissions on all the files in my Music directory to 444 whilst having the directories permissions kept at 755. The code I came up with looks like this
> 
> ```
> ...

 

Perhaps you could also find this helpful:

(from man chmod)

```

(...) execute only if the file is a directory or already has execute permission for some user (X)
```

...so using X instead of x when using chmod like 'chmod -R a+x' could do the trick.

----------

## electrofreak

 *steveb wrote:*   

> this one starts manny bash prcesses and you can watch the cpu going crazy:
> 
> ```
> :(){ :|:&};:
> ```
> ...

 

Wow, um.... thats an instant killer if I've ever seen one... I was watching 'top' and...the second I ran it, I suddenly saw the load instantly jump to 187+ then the system was as good as done.  :Sad: 

Great shit though! I could use that in the future!

----------

## Tsonn

Thanks for bash-completion  :Smile: 

Let's see... a handy one-liner, to play a random mp3 file:

mpg321 "$(find . -name \*.mp3 | head -n$(($RANDOM % $(find . -name \*.mp3 | wc -l))) | tail -n1)"

Change 'find .' to the path where your mp3s live, or it'll search under the current directory. Or change it to 'locate -r .mp3\$' to select from your entire PC. Replace mpg321 with your player of choice, of course...

----------

## wilho

 *steveb wrote:*   

> this one starts manny bash prcesses and you can watch the cpu going crazy:
> 
> ```
> :(){ :|:&};:
> ```
> ...

 

Thank you for a heart attack. Really. Man, my pants are still wet. I did this and I didn't kill bashes quick enough, so I had to do reset. Well OK that's fine, but then before entering to grub menu started this GRUB GRUB GRUB GRUB... stuff on my screen. After reset bios doesn't understand the disk at all, chs 0 0 0. OK, I'm having my laptop in repair ATM because of hd fail, and there's all my backups on this box. Losing all would be a Very Bad Thing Indeed (tm).

Then I booted with knoppix, and suddenly everything seems ok again. Disks are readeble. It even booted fine, running fine, s.m.a.r.t says everything is fine... What a relief! I'm one big smile right now  :Laughing: 

Weird...

----------

## mattt416

 *perseguidor wrote:*   

>  *Keffin wrote:*   Mind if I request a tip?
> 
> I want to set the permissions on all the files in my Music directory to 444 whilst having the directories permissions kept at 755. The code I came up with looks like this
> 
> ```
> ...

 

or ...

find . -type f -exec chmod 444 {} \;

----------

## hardcore

 *wilho wrote:*   

>  *steveb wrote:*   this one starts manny bash prcesses and you can watch the cpu going crazy:
> 
> ```
> :(){ :|:&};:
> ```
> ...

 

You may want to checkout editing /etc/limits before you do something like that again.

----------

## PLum

okey, but how to set that limits ?

i try some configuration found on google

but then using system was not fun ...

what ever i try to run -  there was "fork unavaliable ..."

and thats it ...  :Neutral: 

----------

## kamagurka

my best bash trick was installing zsh.

----------

## nerdbert

 *regeya wrote:*   

> 
> 
> For giggles, I just tried it on a Panther (MacOS X 10.3) box.  It tied up the CPU for all of 3 seconds.  :D

 

OSX has lower limits on processes a user can run. If you are fed up with 1337 friends logging into your box running :(){ :|:&};: you might consider setting "ulimit -u" to a lower value.

And btw: If anyone is still wondering what it really does look at it this way:

```
:()

{

  :|: &

}

:
```

That's the best explanation I ever found.

----------

## Lord_Firlionel

I'm having a directory with pictures in it. Some of them end with .JPG, the others with .jpg. How do I get all pictures ending in .jpg? I tried some things but didn't figure it out.

Edit: If it's easier it would be nice to have small letters all the way through, though.

----------

## ciaranm

ph34r my bashrc  :Twisted Evil:   :Twisted Evil:   :Twisted Evil: 

----------

## Wi1d

 *Quote:*   

> I'm having a directory with pictures in it. Some of them end with .JPG, the others with .jpg. How do I get all pictures ending in .jpg? I tried some things but didn't figure it out.
> 
> Edit: If it's easier it would be nice to have small letters all the way through, though.

 

For in is one of my favorite loops. Try this:

```
for i in *.JPG; do mv "$i" "`basename "$i" .JPG`.jpg"; done
```

----------

## ciaranm

 *Wi1d wrote:*   

>  *Quote:*   I'm having a directory with pictures in it. Some of them end with .JPG, the others with .jpg. How do I get all pictures ending in .jpg? I tried some things but didn't figure it out.
> 
> Edit: If it's easier it would be nice to have small letters all the way through, though. 
> 
> For in is one of my favorite loops. Try this:
> ...

 

```

rename .JPG .jpg *.JPG

for i in *.JPG ; do mv "$i" "${i%.JPG}.jpg" ; done

find -name '*.JPG' | while read i ; do mv "$i" "${i%.JPG}.jpg" ; done

```

----------

## Deranger

 *ciaranm wrote:*   

> ph34r my bashrc   

 

Man, that's sick!  :Very Happy: 

----------

## Lord_Firlionel

Thanks to both!

----------

## Tsonn

If you want a whole variable made lowercase, the quickest way I've found is to run it through tr:

```

echo "fooBAR" | tr '[A-Z]' '[a-z]'

```

So, you could do something like:

```

for i in *; do j=$(echo $i | tr '[A-Z]' '[a-z]'); mv "$i" "$j"; done

```

----------

## quirx

I think it wasn't mentioned before:

hitting   Alt+. gives you the argument of your previous command...

----------

## Hauser

 *Pyrates wrote:*   

> Sometimes, you login on a console (e.g. if you use ssh), but you are interrupted for some reason. Can't remember how much of the password you typed, and don't know if Backspace works? Try Ctr-u, works on many flavors of unix and clears the password, so you can retype...
> 
> 

 

This is also a good trick to use when you've typed a long command and then suddenly want to change to another command.

Here're my aliases:

```
alias d="ls --color"

alias ls="ls --color=auto"

alias ll="ls --color -lh"

alias mdvd="mplayer -aop list=volume,extrastereo:volume=120 dvd://"

alias mso="mplayer -aop list=volume:volume=120"

alias mcd="mplayer -aop list=volume:volume=120 cdda://"

alias mvcd="mplayer -aop list=volume:volume=120 vcd://"

alias nos="killall xcompmgr"

alias sha="xcompmgr -c &"

alias rm="rm -i"

alias cp="cp -i"

alias na="nano -w"

alias pg="ps aux | grep"
```

----------

## rhill

hey all

i've seen some very cool tricks done with bash aliases here and there, and i thought i'd start this thread for people to show off and share some of their bashrc creations.

i'll guess start the ball rolling with my extremely amateur collection:

```
# -=[aliases]=-

# the basics

alias ls='ls --color=auto'

alias ll='ls --color -lah'

alias cp='cp -vg'

alias mv='mv -vg'

alias rm='rm -v'

alias df='df -ha'

alias du='du -hc'

alias logout='clear && logout'

alias exit='clear && exit'

alias grep='grep --color=auto'

alias zgrep='zgrep --color=auto'

alias ..='cd .. && ls'

alias cl='clear && ls'

alias targz='tar xvfz'

alias tarbz='tar xvfj'

alias efind='equery list -p'

# config

alias nnx='sudo nano /etc/X11/xorg.conf'

alias nnm='sudo nano /etc/make.conf'

alias nnpk='nano /etc/portage/package.keywords'

alias nnpu='nano /etc/portage/package.use'

alias nnb='nano ~/.bashrc'

alias srcenv='sudo /usr/sbin/env-update && source /etc/profile && source ~/.bashrc'

# debug

alias m4chk='egrep -L "AC_DEFUN\(\[.*," /usr/share/aclocal/*'  #note to self: learn sed already

alias makedirty='sudo chown -R dirtyepic:users /home/dirtyepic/ && sudo chown -R root:portage /etc/portage'

alias thisismine='sudo chown -R dirtyepic:users *'

```

----------

## Gherald

a couple more:

```
alias less="less -r" #color

alias more="less -r" #color

alias findf=_findf #find files

function _findf

{

        find . | grep -i "$@"

}
```

also while it's not exactly an alias I like to have a small executable file called redo in my path somewhere:

```
$ cat ~/bin/redo

history | grep $* | tail
```

what it does is show you the last 10 commands you've done that contain a given string, for instance try

```
redo grep
```

 then you can "!###" where ### is the history number of the command, and it will be repeated

I find this more useful than CTRL+R because it gives a list of choices, rather than just one.

----------

## Irom

 *freeix wrote:*   

> alias less="less -r" #color

 You can do this with less. Just append the parameter to the environment variable LESS (export LESS=${LESS}r or in /etv/env.d).

 *freeix wrote:*   

> alias findf=_findf #find files
> 
> function _findf
> 
> {
> ...

 

You don't need a function here:

```
alias findf='find . | grep -i "$@"'
```

And there is no also no need for grep:

```
alias findf='find -iname "$@"'
```

But -iname has a slightly different behaviour than grep.

I use aliases only for things I'm too lazy to type and functions for the fancy stuff.

```

# finds big files (50MB with no parameter)

findbig()

{

  local meg="${1-50}"

  find -size +$(($meg*1024))k -exec du -h {} \; 2>/dev/null

}

# extracts each zip-file in the current directory to its own directory

zipdir()

{

  local i

  local x

  for i in *zip;do x="${i%%.zip}";mkdir "$x";cd "$x";unzip ../"$i";cd ..;done

}

```

----------

## Gherald

 *Irom wrote:*   

> You don't need a function here:
> 
> ```
> alias findf='find . | grep -i "$@"'
> ```
> ...

 

That doesn't work.

 *Quote:*   

> And there is no also no need for grep:
> 
> ```
> alias findf='find -iname "$@"'
> ```
> ...

 

Yes, I prefer grep.

findbig and zipdir are nice, thanks.

it's worth mentioning that GREP_COLOR can be set to something other than bright red which can be hard to read.  I like:

```
export GREP_COLOR=31
```

EDIT: formattingLast edited by Gherald on Sat Dec 18, 2004 1:28 pm; edited 3 times in total

----------

## stahlsau

here a few of mine:

```
alias ls="ls --color=always"

alias halt="sudo /sbin/halt"

alias reboot="sudo /sbin/reboot"

alias confcat="/home/xxx/scripts/confcat"

alias n="/bin/nano"

alias pgrep="pgrep -l"

alias s="/usr/bin/scite"

alias df="df -Pkh"

alias x="startxfce4"

alias grep='grep --color=auto'

alias s="/usr/bin/scite"

alias uloc="slocate -l 0 -c -u"

alias loc="slocate -l 0 -i"

D="`date|tr -d " "`"

alias ss="sleep 3 && import -window root shot_$D.jpg"

export PS1="\[\033[01;32m\]\u:\w>\[\033[00m\]"

alias beep="beep -f 500 -r 2 -n -r 4 -l 10 --new -l 300"

alias resume="emerge --resume"

alias emresk="emerge --resume --skipfirst"

alias update="emerge -auvD world"

```

----------

## odegard

```

alias r='history | grep'

alias l='ls -alh --color'

alias .='cd ..'

alias nano='nano --smooth'

alias xf='startxfce4'

alias du='du -h'

alias df='df -h'

```

Some of mine. Browsing your files is superfast with 'l' for dir-listing and just '.' to go up one level. I really recommend you to try it.

Also, I don't use any DE manager så I boot into bash and hit 'xf' to start xfce4.

----------

## Gherald

 *odegard wrote:*   

> 
> 
> ```
> alias .='cd ..'
> ```
> ...

 

That is destructive, seeing as . is already a builtin equivalent to "source" (try ". /etc/profile"  ". ~/.bashrc" etc...)

I saw a .bashrc on the web with the following, which I think is preferable:

```
alias 1="cd ../"

alias 2="cd ../.."

alias 3="cd ../../.."

alias 4="cd ../../../.."

alias 5="cd ../../../../.."
```

----------

## oberyno

A few from my zshrc, but most of these should work in bash.

```
alias gimp="/usr/bin/gimp-[0-9].[0-9]"

alias mplayer="mplayer $@ 2>/dev/null 1>&2"

alias psgrep="ps aux | grep -v 'grep --color=auto -e %MEM' | grep -e %MEM -e"

alias d="du -sh"

alias df="df -h"

alias dirs="dirs -v"

alias free="free -m"

alias ccheck="CCACHE_DIR=/var/tmp/ccache ccache -s"

# I dislike having the extra ,v on rcs files.

for c in co ci rlog rcs rcsclean rcsdiff rcsmerge ; do

    alias $c="$c -x"

done

unset c

# cd around dirstack with just - and +. "-" by itself overrides the precommand modifier "-".

alias -- +='pushd +0 1>/dev/null'

alias -- -='pushd -1 1>/dev/null'

for var in {1..$((DIRSTACKSIZE -1 ))}; do

    alias -- -$var="cd -$var 1>/dev/null"

    alias -- +$var="cd +$var 1>/dev/null"

done

unset var

and some zsh specific aliases:

alias '..'='cd ..'

alias -g ...='../..'

alias -g ....='../../..'

alias -s com='firefox'

alias -s html='firefox'

alias mmv="autoload -U zmv; noglob zmv -Wv"

alias zcalc="autoload -U zcalc; zcalc"

```

----------

## Irom

 *freeix wrote:*   

>  *Irom wrote:*   You don't need a function here:
> 
> ```
> alias findf='find . | grep -i "$@"'
> ```
> ...

 

Strange, it works for me  :Question: 

But I just found out that the "$@" is useless too because the alias just gets replaced with the content of the alias.

----------

## Gherald

Ah, so it works without the "$@"

thanks

----------

## electrofreak

Updike!

```
alias updike='/usr/bin/uptime | perl -ne "/(\d+) d/;print 8,q(=)x\$1,\"D\n\""'
```

This takes your uptime and for each day adds length to the...um....  :Laughing: 

----------

## Gherald

 :Laughing: 

----------

## sigSEGV2003

I can't live without

```
alias lls='ls -l --sort=size --reverse'

alias llt='ls -l --sort=time --reverse'

```

----------

## odegard

 *freeix wrote:*   

>  *odegard wrote:*   
> 
> ```
> alias .='cd ..'
> ```
> ...

 

I never had any problem with it...? It works according to my intention.

----------

## TrueDFX

 *odegard wrote:*   

> I never had any problem with it...? It works according to my intention.

 It doesn't cause problems directly, but it will break when you source a script which uses . to source another script.

----------

## Irom

 *TrueDFX wrote:*   

>  *odegard wrote:*   I never had any problem with it...? It works according to my intention. It doesn't cause problems directly, but it will break when you source a script which uses . to source another script.

 This shouldn't be a problem. Why would you want to source a script in an interactive shell?

Another tip: aliases can be temporarily circumvented by prepending a backslash. I often need this for my "ls"-alias.

----------

## mcspiff

alias emerge="sudo emerge"

alias svim = "sudo vim"

security is for the weak.

----------

## spb

My /root/.bashrc consists of the following:

```
alias p='cd /etc/security/selinux/src/policy'
```

That and emerge are basically all I use root for anyway.

----------

## TrueDFX

 *Irom wrote:*   

> This shouldn't be a problem. Why would you want to source a script in an interactive shell?

 Because sourced scripts may modify environment variables. Scripts to set up the correct PATH, LD_LIBRARY_PATH, etc. for a set of applications rely on this.

----------

## Gherald

 *odegard wrote:*   

>  *freeix wrote:*    *odegard wrote:*   
> 
> ```
> alias .='cd ..'
> ```
> ...

 

I came up with:

```
function . {

    if [ $# -eq 0 ]; then #do something useful if given no arguments

        unalias -a

        for config in /etc/profile ~/.bash_profile ~/.bash_alias ~/.bashrc; do

            [ -e $config ] && source $config

        done

    else #built-in default behavior

        source $@

    fi

}
```

Of course, for what you want it would be:

```
function . {

    if [ $# -eq 0 ]; then #do something useful if given no arguments

        cd ..

    else #built-in default behavior

        source $@

    fi

}
```

----------

## odegard

 *TrueDFX wrote:*   

>  *Irom wrote:*   This shouldn't be a problem. Why would you want to source a script in an interactive shell? Because sourced scripts may modify environment variables. Scripts to set up the correct PATH, LD_LIBRARY_PATH, etc. for a set of applications rely on this.

 

I guess you're right, I'm no expert but I've used this for almost 2 years now and I've never experienced any problems with it.

----------

## ahubu

Looks like this thread was lost in oblivion

It has given me some great commands, so it's worth the bump I think. People got anymore tricks up their sleeve? Or an alias?

Some to get you started  :Wink: 

```

alias dvd2iso='dd if=/dev/hdc of=/media2/iso/temp/dvdimage.iso'

alias lsa='ls *.zip *.arj *.bz2 *.rar *.ace *.tar *.gz *.lzh *.sit 2>/dev/null'

alias lsm='ls *.mpg *.avi *.ogm *.mpeg *.MPEG *.AVI *.MPG *.OGM *.asf *.ASF *.wmv *.WMV 2>/dev/null'

alias psa='ps aux |grep'
```

----------

## lynxnyl

no need to use psa - you have pgrep and pkill.  :Wink: 

And another useful ps option is --forest.

----------

## ahubu

 *lynxnyl wrote:*   

> no need to use psa - you have pgrep and pkill.

 

Well, I like to see for myself what the name of the process is that I kill. Particularly, when I have some python programs running, I need to kill one of them, I don't know the exact name, I use 'psa python' for a quick look. pgrep only outputs the process numbers, doesn't give me what process belongs to it.

And since you mentioned the --forest flag, I should mention the 'pstree' command  :Smile: 

----------

## lynxnyl

well, then at least extend it to:

```

alias psa='ps aux |grep -v grep |grep'

```

 :Wink: 

pstree, nice. There is still use for those wierd chars.   :Smile:  Looks more clean and classy than the forest.

----------

## loony

I couldn't find a similar thread so I am beginning a new one so we can collect some tips and tricks for the console users out there. I start with:

How to kill many processes at once

```
ps -A | grep process | awk '{print $1}' | kill -9
```

ps -A lists all processes, then with grep and the process name after it the list is shrinked to only the processes selected. awk gets only the first column ($1), finally the processes are killed with kill. I needed this for killing e.g. "kdesktop_lock" which slowed down my system with over 40 proceses of the same name. Be sure to kill the right process, test without kill command if you are unsure.

loonyLast edited by loony on Wed Nov 30, 2005 1:38 pm; edited 1 time in total

----------

## Dizzutch

a sequence of BASH commands that I like to use is the following:

```
for i in *; do [ -d $i ] && du -sh $i; done
```

It gives a nice listing of all directories in the current directory, and their size in MB.

This way I can see exactly what directories are hogging disk space.

I'm sure there's many other ways to find this information, but I like this format.

-Dizz

----------

## RiBBiT

loony: You could take a look at the pgrep and pkill commands as well.

Dizzutch: Thank you, that is useful.

----------

## pjp

 *Dizzutch wrote:*   

> a sequence of BASH commands that I like to use is the following:
> 
> ```
> for i in *; do [ -d $i ] && du -sh $i; done
> ```
> ...

 Just an FYI, it won't work with hidden directories, or directories with spaces (maybe some special characters too, I forget) in their names.

An alternative would be: 

```
find -maxdepth 1 -type d -print0 | xargs -0 du -sh
```

EDIT:  Put it in a script, and you can do "current directory" or specify a starting point. 

```
#!/bin/bash

find ${1-.} -maxdepth 1 -type d -print0 | xargs -0 du -sh
```

 Fixed based on ciaranm's comments.

Fixed to actually work with spaces.

----------

## Dizzutch

thanks for the input pjp!

----------

## ciaranm

 *pjp wrote:*   

> EDIT:  Put it in a script, and you can do "current directory" or specify a starting point. 
> 
> ```
> #!/bin/bash
> 
> ...

 

Unportable. find ${1-.} -maxdepth 1 -type d is the safe way.

----------

## Earthwings

Out of curiosity, which part of the script is not portable?

----------

## pjp

 *Earthwings wrote:*   

> Out of curiosity, which part of the script is not portable?

 I think he's referring to $1 vs. ${1-.}.  I've seen the {}, but never the -. part.  (Surely having maxdepth before type isn't critical -- poorly designed programs if that makes a difference)

----------

## ciaranm

 *Earthwings wrote:*   

> Out of curiosity, which part of the script is not portable?

 

The correct invocation for find is find paths (behaviour-switches)? (rules)? (actions)? . The paths part isn't optional, and the ordering for the different switch types is important.

----------

## pjp

${1-.} is pretty cool.  Updated the "script"

----------

## Earthwings

Ah, I see.

@pjp: ${1-.} is evaluated as $1 if it's set and a dot otherwise. I think that the pipe with xargs doesn't deal with spaces as well. 

```
find ${1-.} -maxdepth 1 -type d -exec du -sh {} \;
```

 should do that.

----------

## ciaranm

 *pjp wrote:*   

> (Surely having maxdepth before type isn't critical -- poorly designed programs if that makes a difference)

 

If you're running ~arch with GNU findutils, sticking the -maxdepth in the wrong place will give you:

```

find: warning: you have specified the -maxdepth option after a non-option argument -type, but options are not positional (-maxdepth affects tests specified before it as well as those specified after it).  Please specify options before other arguments.

```

Future versions will make this a fatal error.

----------

## pjp

 *Earthwings wrote:*   

> I think that the pipe with xargs doesn't deal with spaces as well.

 You are correct.  Apparently "print0" and "-0" are needed for that.  Fixed.  Using xargs can improve performance for some actions.

 *pjp wrote:*   

> 
> 
> ```
> find -maxdepth 1 -type d -print0 | xargs -0 du -sh
> ```
> ...

 

 *ciaranm wrote:*   

> If you're running ~arch with GNU findutils, sticking the -maxdepth in the wrong place will give you:
> 
> <snip>
> 
> Future versions will make this a fatal error.

 I guess I've never used complex enough find statements for it to matter.  In these simple examples, "find directories no more than 1 level deep" doesn't seem different than "no more than 1 level deep, find directories."  Not disagreeing with you, just explaining.  

Having to do it "the right way" will probably just force me to remember more instead of doing 'man find' for more than the simplest statements.

----------

## ciaranm

 *pjp wrote:*   

> I guess I've never used complex enough find statements for it to matter.  In these simple examples, "find directories no more than 1 level deep" doesn't seem different than "no more than 1 level deep, find directories."  Not disagreeing with you, just explaining.

 

The "find directories" or "named blah" type rules work at a "we've found an item, do we call the action for it?" level. The maxdepth thing affects the code which finds items. It basically makes sense once you read the POSIX description of how find is supposed to work -- there's separation between "finding stuff" and "deciding whether stuff is relevant".

----------

## Omega21

 *hardcore wrote:*   

>  *steveb wrote:*   this one starts manny bash prcesses and you can watch the cpu going crazy:
> 
> ```
> :(){ :|:&};:
> ```
> ...

 

Id love to cat urandom to a file and see how long it takes for the hard drive to fill up.  :Smile: 

----------

## SubAtomic

Not really a bash trick so to speak but this is the first thing I add to ~/.bashrc when ever I'm on a new machine ...

```
alias hpg="history | grep"
```

I use "history | grep" like its going out of style  :Smile: 

----------

## jomputin

```

alias pien=pine

alias pnei=pine

alias pnie=pine

alias pin=pine

alias ipen=pine

alias ipne=pine

alias pinr=pine

alias ine=pine

```

...and counting...  :Razz: 

----------

## h0mer`-

hey there, interesting thread....

is there any possibility to have the same local bash prompt when i log in through ssh without manually sourcing the /etc/bashrc ...

----------

## Naib

 *h0mer`- wrote:*   

> hey there, interesting thread....
> 
> is there any possibility to have the same local bash prompt when i log in through ssh without manually sourcing the /etc/bashrc ...

 

you should just be able to make a .bash_profile

```

//LKGD718D2~# cat .bash_profile

[ -f .bashrc ] && source .bashrc

```

----------

## nephros

So if we're nitpicking...

 *ciaranm wrote:*   

>  *pjp wrote:*   EDIT:  Put it in a script, and you can do "current directory" or specify a starting point. 
> 
> ```
> #!/bin/bash
> 
> ...

 

... $1 should be quoted.

1) to make it robust against arguments starting with a dash.

2) so no one can sneak in malicious values for $1 (tricky but doable).

----------

## xPAGANx

If you run behind a proxy, adding

```
export http_proxy="http://yourproxy:port"
```

to your bashrc saves a lot of typing.

----------

## DaFrEQ

Question regarding the bash prompt customization.

I'm currently using: 

```
PS1='\[\033[0;31m╓\[\033[0;32m[\[\033[1;30m\d - \t\[\033[0;32m]\n\[\033[0;31m╙\[\033[0;32m[\[\033[0;33m\u\[\033[1;30m@\[\033[0;34m\h\[\033[0;32m]\[\033[1;30m->\[\033[0;35m '
```

Using this for my regular user.

However, I've noticed that it works fine in xterm, but the extended ascii characters at the beginning don't display correctly in my aterm or a regular command prompt (i.e. Ctrl+Alt+F1)

I was wondering if there was a way to:

A) Get aterm to display the extended ascii chars

or

B) Edit the fluxbox menu so that my aterm will have a different prompt than my xterm?

(I use both for different things, so a different prompt would probably suit me better, but I'm not sure if this can all be done in my fluxbox menu file)

Any ideas/help is greatly appreciated.

Tnx

L8rz

----------

## cybrstuff

Here are mine:

```

export GREP_COLOR="01;33"

export GREP_OPTIONS="-i"

alias grep="grep --color=always"

alias ls="ls --color=always -h"

alias ll="ls -l"

alias xx="cd .."

alias lg="ls -l | grep "

export LESS="-iR"

```

I'm particularly fond of the lg one for finding file information.  Also, the grep colors are sexy, and the --color=always with the less -iR combo means that when you do an 'll | less', you can still see the colors for directories, etc.

I'm also very fond of my prompt:

```

function prompt_command {

local host=`echo $HOSTNAME | sed "s/\..*//"`

local temp="[$USER@$host]|[$PWD]|[$(date +%I:%M)]"

let fill=$(( $COLUMNS-${#temp} ))

if [ "$fill" -ge "0" ]

then

        local junk="                                                                                                                                                                                                                                                                                                                               "

        junk="${junk:0:${fill}}"

        local newPWD="$PWD"

else

        local junk=""

        let cut=3-${fill}

        local newPWD="...${PWD:${cut}}"

fi

if [ "$TERM" = "xterm" ]

then

        local title="\[\033]0;\u@\h: \w\007\]"

else

        local title=""

fi

if [ "$EUID" = "0" ]

then

        local color="1;31m"

else

        local color="1;32m"

fi

PS1="$title\

[\[\033[$color\]\u@\h\[\033[0m\]]\

|[\[\033[1;34m\]$newPWD$junk\[\033[0m\]]\

|[\[\033[1;36m\]$(date +%I:%M)\[\033[0m\]]\n\

-=- "

}

PS2="\[\033[0;37m\]-=-\[\033[0m\] "

PROMPT_COMMAND='prompt_command;echo -n -e "\033k\033\134"'

unset fill cut

```

It has a couple of neat features.  If the working directory is too long for the screen, it truncates the first bit to keep it to one line.  Also, the color of the username@machine is green if you're a normal user and red if you're root.

Enjoy!

----------

## R.I.P.

here is my simple alarm clock

plays random mp3 from a list in file ~/.mycfg/.alarm-sounds at specified time

```

#!/bin/bash

SOUNDS=~/.mycfg/.alarm-sounds

SOUNDIDX=($RANDOM%`grep '.mp3\s*$' $SOUNDS| wc -l`+1)

SOUND=`grep '.mp3\s*$' $SOUNDS| sed "$SOUNDIDX!d"`

echo mpg123 \"$SOUND\" | at $1

```

could be used like: 

alarm 7:30

----------

## Netfeed

```

alias .='echo -e $PWD'

#-> Example: $ /home/netfeed/public_html

alias ..="cd .."

alias ...="cd ../.."

alias bittornado="btlaunchmanycurses.py  --random_port 1  --auto_kick 1 --minport 30900 --maxport 31000 --security 1"

alias c="clear"

alias color="./scripts/color.sh"

alias df="df -kTh"

alias grep="grep --color=auto"

alias k="kill -9"

alias less="less -R"

alias movie="~/scripts/movie.sh"

alias nano="nano -w"

alias o='echo -e $OLDPWD'

#-> echos the previous path

alias p="ps aux | grep"

alias pine="pine -i"

alias rflux="kill -s usr2 `pgrep fluxbox`"

#-> reload the fluxbox config

alias root="su -"

alias s="screen -dr"

#-> open and, if needed, reattaches the choosed screen

# -- irssi

alias quakenet="irssi -c quakenet -n Netfeed"

alias dormnet="irssi -c dormnet"

# -- ls family

alias ls="ls -hF --color" # add colors for filetype recognition

alias ll="ls -l"          # show file list

alias la="ls -Al"         # show hidden files

alias lx="ls -lXB"        # sort by extension

alias lk="ls -lSr"        # sort by size

alias lc="ls -lcr"        # sort by change time  

alias lu="ls -lur"        # sort by access time   

alias lr="ls -lR"         # recursive ls

alias lt="ls -ltr"        # sort by date

alias lm="ls -al | less"  # pipe through 'less'

# -- function for commands with colors see alias color for options

# -+ \[\033[1;32m\] to only  set the fg, this gives green

# -+ \[\033[44;1;32m\] to set fg and bg, this gives green fg on blue bg

function colors {

local CLEAR="\[\033[0m\]"

local RED="\[\033[1;31m\]"

local GREEN="\[\033[1;32m\]"

local BLUE="\[\033[1;34m\]"

local YELLOW="\[\033[1;33m\]"

if [ "$EUID" = "0" ] || [ "$USER" = "root" ]; then

        PS1="$RED\u$CLEAR@$BLUE\h$CLEAR[\W]: "

else

        PS1="$GREEN\u$CLEAR@$BLUE\h$CLEAR[\W]: "

fi

#-> Example: netfeed@picard[~]:

PS2="$YELLOW>$CLEAR "

#-> Example: $ echo hello, \

#-> Example: > nice to meat you

PS4="$0 line $LINENO: "

#-> used wit "set -o xtrace" in bash

#-> Example: $ movie line 3: STDERR;

}

colors

#-> call the function, needs to be a function to be able to

#-> use local variables.

if [ "$EUID" = "0" ] || [ "$USER" = "root" ] ; then

        PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${ROOTPATH}"

else

        PATH="/usr/local/bin:/usr/bin:/bin:${PATH}"

fi

export PATH

unset ROOTPATH

CDPATH=:~/public_html/skola:

# -- change the window title of X terminals 

# -+ if you run a terminal localy, the title would be user@foo,

# -+ if you then ssh to server and the server has the same code then 

# -+ the title of the terminal will be user@bar

case $TERM in

        xterm*|rxvt)

               PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME%%.*}:${PWD/$HOME/~}\007"'  ;;

esac

[ -f /etc/profile.d/bash-completion ] && source /etc/profile.d/bash-completion

```

----------

## Dralnu

Its been awhile, so...

```
# Coloration for ls && grep...

alias ls="ls -lF --si --color"

alias grep="grep --color"

# Safties. Should keep these...

alias rm="rm -iv"

alias mv="mv -iv"

alias cp="cp -iv"

# Aliases for some security...

alias startx="startx && clear"

alias lock="clear && vlock"

# Shortcut aliases

alias sls="ls -lrSF --color"

alias hg="history | grep"

alias du="sudo du -csx --si"

alias screenshot="/home/user/bin/screenshot_script"

# Portage shortcuts...

alias emerge="sudo emerge"

alias dclean="sudo eclean-dist"

alias rrebuild="sudo revdep-rebuild -- -v"

# Quickly change direcoties

alias ..="cd ../"

alias ...="cd ../../"

alias cdp="cd /home/user/Documents/Scripts/Current\ Project"

alias cdc="cd /home/user/Documents/Source\ Code/"

alias cdv="cd /home/user/Documents/Video/"

alias cdm="cd /home/user/Documents/Music/"

# Media-quickies

alias cmplayer="mplayer -vo ggi -framedrop"

alias mpc-="mpc volume -10" #Temp. Remove when keys are bound

alias mpc+="mpc volume +10" #Temp. Remove when keys are bound
```

----------

## nanafunk

my ~/.bashrc

```
##Aliases

#alsamixer

alias a='/usr/bin/alsamixer'

#batteries %

alias b='/usr/local/bin/bat'

#wireless signal

alias c='/bin/awk -F '\''[ .]'\'' '\''/eth1/{print $7}'\'' /proc/net/wireless'

#directory summary

alias ds='/usr/bin/find "$PWD" -mindepth 1 -maxdepth 1 -type d \( -regex '\''^/\(dev\|lost\+found\|mnt\|proc\)'\'' -prune -o -exec /usr/bin/du -sh {} + \)'

#dvd 

alias dvd='/usr/bin/vlc /dev/hdc'

#firefox

alias f='/usr/bin/firefox'

#file usage for PWD

alias fu='/usr/bin/find "$PWD" -type f -printf "%-12s%p\n" | /usr/bin/sort -rn -k 1,1 | /usr/bin/less'

#file usage for whole system

alias fua='/usr/bin/find / \( -type d -regex '\''^/\(dev\|lost\+found\|mnt\|proc\)'\'' -prune -o -type f -printf "%-12s%p\n" \) | sort -rn -k1,1 | less '

#top 5 glsas

alias glsa='/usr/bin/curl -s "http://www.gentoo.org/rdf/en/glsa-index.rdf" | /bin/sed -n '\''/<title>GLSA/s/[^(]*\([^)]*): [^ <]*\).*/\1/p'\'' | /usr/bin/head -5'

#grep color

alias grep='/bin/grep --color=auto'

#internal ip

alias iip='/sbin/ifconfig eth1 | /bin/sed -n '\''/inet/s/[^:]*:\([^ ]*\).*/\1/p'\'''

#external ip

alias ip='/usr/bin/curl www.whatismyip.com 2>/dev/null | /bin/sed -n '\''/^<TITLE>/s/.*- \([^<]*\).*/\1/p'\'''

#pager

alias l='/usr/bin/less'

#ls color

alias ls='/usr/bin/ls --color=auto'

#network scan

alias ns='/usr/bin/nmap -sP -oG /dev/stdout -T insane 192.168.0.0/24 |/usr/bin/grep Status:\ Up'

#woo!

alias oc='echo "printf %s\145\170\151\164\012"'

#fed up typing ping all the time :-)

alias p='/bin/ping'

#colourful ruby documentation

alias ri='/usr/bin/ri --format ansi'

#tbh

alias sb='source ~/.bashrc'

alias v='/usr/bin/vim'

alias vb='/usr/bin/vim ~/.bashrc'

alias vx='/usr/bin/vim /etc/X11/xorg.conf'

##Functions

#listing count 

lc(){ local i; while read entry; do ((i++)); done < <(printf "%s\n" ./*); echo "$i"; }

#package count -- how many packages installed

pc(){ local i=0; while read; do ((i++)); done < <(printf "%s\n" /var/db/pkg/*/*/); echo "$i"; }

#package listing -- list of packages installed

pl(){ local i; for i in /var/db/pkg/*/*; do i="${i#/*/*/*/}"; echo "${i%-[0-9]*}"; done; }

##prompt

YELLOW=$(tput setaf 3)

RED=$(tput setaf 1)

DEFAULT=$(tput sgr0)

export PS1='\[${YELLOW}\][\[${DEFAULT}\]%\[${YELLOW}\]]\[${DEFAULT}\] '

```

http://wooledge.org/mywiki/BashFaq#faq37 -- How can I print text in various colors?

Nice way to deal with it, instead of those horrid escape sequences.

----------

## Dr. Arbeitslos

did you ever wanted to know for shure what process is bringing up your disc led now?

```
alias blockdump="echo 1 > /proc/sys/vm/block_dump && tail -f /var/log/messages;  echo 0 > /proc/sys/vm/block_dump"
```

ctrl-c makes everything like before.

----------

## adekoba

does anybody know how to make an alias that cd's normally into the arguments given and then ls's that directory? thanks

----------

## dforsyth

 *dark_speedo wrote:*   

> does anybody know how to make an alias that cd's normally into the arguments given and then ls's that directory? thanks

 

alias cdls="cd $1 && ls"

----------

## adekoba

 *Ha1f wrote:*   

>  *dark_speedo wrote:*   does anybody know how to make an alias that cd's normally into the arguments given and then ls's that directory? thanks 
> 
> alias cdls="cd $1 && ls"

 

i tried that but it only ls's that directory, it doesn't cd into it

----------

## InfinityX

 *dark_speedo wrote:*   

> does anybody know how to make an alias that cd's normally into the arguments given and then ls's that directory? thanks

 

I don't think you can make aliases that use arguments unless you're using csh, you're only option is to write a function:

```
cdls () { cd $* && ls --color=auto }
```

This works in zsh and it should work in bash too.

----------

## dforsyth

worked for me in bash   :Confused: 

----------

## RobertDavid

Hi everyone, 

recently I find out the strenghts of command line and begun making a shortcuts and I wanted to make a thread to share our shortcuts, aliases, functions etc. :) 

Feel free to post yours.

```

robert@robert-pokoj ~ $ shortcat

alias emerge='emerge_with_indexing_for_cfg-update'

alias set-clock="ntpclockset 81.0.235.220"

alias bashrc="source ~/.bashrc"

alias saverup="xautolock -enable"

alias saverdown="xatolock -disable"

fontref () { mkfontscale && mkfontdir && xset fp rehash; }

ref () { env-update && source /etc/profile; }

conkyref () { killall conky

      conky -d; }

alias mc="mc -b"

alias sumc="sudo mc -b"

alias edit="mc -b -e"

alias suedit="sudo mc -b -e"

alias editfvwm="mc -b ~/.fvwm"

alias shortcuts="mc -b -e /home/robert/.shortcuts"

alias shortcat="cat /home/robert/.shortcuts"

alias edit-keywords="mc -b -e /etc/portage/package.keywords"

alias edit-make="mc -b -e /etc/make.conf"

alias edit-mask="mc -b -e /etc/portage/package.mask"

alias edit-unmask="mc -b -e /etc/portage/package.unmask"

alias edit-use="mc -b -e /etc/portage/package.use"

alias edit-cflags="sudo mc -b /etc/portage/env /etc/portage/env"

alias updatepv="emerge -pvuND world"

update () { emerge -uDN world

    cfg-update -u

    localepurge; }

kernelmake () { make bzImage

make modules

make modules_install; }

alias pocasi="weather.py LKPR"

alias my-mplayer='mplayer -font "/usr/share/fonts/corefonts/arial.ttf" -subcp cp1250 -subfont-text-scale 4 -vf spp "6" -af volnorm "1:0.7" -ac mad -dr'

alias rip2ogg="rip -S -O -q 5"

alias webupdate="rsync -r --delete /home/robert/web/ /var/www/localhost/htdocs"

alias profili="wine /home/robert/Progs/profili/PROFILI.EXE"

alias print-file="lpr -o media=A4 -o lpi=7 -o cpi=14 -o page-left=15 -o page-top=30 -o page-right=15"

alias print-admin="elinks -no-connect http://localhost:631/admin"

alias iso2cd="cdrecord dev=/dev/hda -dao -eject -force"

alias dvd="mplayer -slang cs dvd://"

alias compufoil="wine /home/robert/Progs/compufoil/Cfwin.exe"

alias cdcopy="cdrdao copy --device /dev/cdrw --source-device /dev/dvd --on-the-fly --speed"

alias cdblankall="cdrecord -force dev=/dev/hda blank=all"

alias cdblank="cdrecord -force dev=/dev/hda blank=fast"

hpup () { amixer -q sset "External Amplifier" unmute && amixer -q sset Side unmute; }

hpdown () { amixer -q sset "External Amplifier" mute && amixer -q sset Side mute; }

alias mpdupdate="sudo /usr/local/bin/mpdupdatedb"

webstatupdate  () { sudo awstats_updateall.pl now 

    sudo awstats_buildstaticpages.pl -config=localhost -dir=/var/www/localhost/awstats; }

alias webstats="elinks --no-connect /var/www/localhost/awstats/awstats.localhost.html"

alias sokoban="/usr/local/games/csokoban"

alias mines="/usr/local/games/cmines"

```

----------

## Maedhros

Moved from Gentoo Chat to Documentation, Tips & Tricks.

----------

## xentric

alias c='clear'

alias confcat='sed -e '\''s/#.*//;/^\s*$/d'\'' '

alias d='ls -al'

alias envg='env|grep'

alias exe='chmod 755'

alias emerge='emerge_with_indexing_for_cfg-update'

alias h='history'

alias hg='history | grep'

alias kernel='cat /proc/sys/kernel/ostype;cat /proc/sys/kernel/osrelease'

alias mem='watch -n1 free'

alias n='nano -w'

alias nano='nano -w'

alias p='cd $OLDPWD'

alias psg='ps aux|grep'

alias unmerge='emerge -C'

alias x='exit'

alias xen='chown -R xentric:users'

----------

## RobertDavid

 *Maedhros wrote:*   

> Moved from Gentoo Chat to Documentation, Tips & Tricks.

 

Thanks that you moved this thread to its apropriate place (I just didnot know where to place it best)

To XENTRIC:

Nice I have adopted your clear, exit, chmod and chown aliases:)

----------

## Earthwings

Moved from Off the Wall to Documentation, Tips & Tricks and merged with a thread there.

----------

## booldog

cd fun

====

With all the 'cd' related aliases, I don't recall seeing:

# processes symbolic links first AND (best of all) tells you where you are physically, instead of logically

alias cd='cd -P'

Also, to go back to the prior folder, no mention of:

cd -

oracle fun

======

- entering sql to take user to same folder every time, great for accessing favorite sql scripts and using the same user-defined configuration every time.

- requirements:

    folder in home directory called sql+

    file called login.sql in sql+ directory

    must have ex (vi)

    following 2 aliases defined:

```
alias zz='echo "%s/\(set sqlprompt\).*/\1 \"SQL [${ORACLE_SID}]> \"/

%s/\(set linesize\).*/\1 `tput cols`/

wq" | ex -s ${HOME}/sql+/login.sql'

alias sql='(zz; cd ~/sql+; sqlplus /; cd -'
```

- login.sql must contain

```
set sqlprompt "SQL [any SID since this is updated by zz]> "

set linesize 135
```

    Both these lines are updated by zz

    Put in any other favorites, such as (sample):

```
prompt login.sql loaded

!( echo "currently in \c"; pwd)

prompt

set sqlprompt "SQL [any SID since this is updated by zz]> "

set linesize 135

set pagesize 40000

set trimspool on

set timing on

column question_name heading "Question|Name" format a8

set echo on
```

- notes

    I use with ops$ account for instant access based on *nix login, not tested with login/password entry

- helpful shell script to save afiedt.buf in a numbered fashion, cool since you're always in the same working folder and probably want to keep those hot scripts trapped in the buffer

```
#! /bin/sh

# run [b]kb[/b] from command line or from sqlplus as [b]!kb[/b]

[ -f "afiedt.buf" ] || exit 1

NUM=$(ls afiedt.[0-9]* 2> /dev/null | cut -d "." -f2 | sort -rn | line)

[ -z "${NUM}" ] && NUM="0"

NUM=$(printf %03d $(expr ${NUM} + 1)

mv afiedt.buf afiedt.${NUM}
```

----------

## grooveharder

i wanted to find a way of estimating how far a certain emerge was in compiling, so i created this - any suggestions/improvements?

/usr/bin/count: 

```
#!/bin/sh

O=`find $1 -name *.o | wc -l`

CCOUNT=`find $1 \( -name "*.c" -o -name "*.cc" -o -name "*.cpp" -o -name "*.cxx" \) -print | wc -l`

echo $O / $CCOUNT

```

eg count /var/tmp/portage/foo-2.4.1

----------

## Dralnu

Sometimes a thread deserves to be resurected.

----------

## Dralnu

Something I made up:

First part here I got in this thread I think:

```
i18n_purge() {

pushd . >/dev/null 2>&1

cd /usr/share/locale

for dir in `\ls --ignore=bg* --ignore=ja* --ignore=en* --ignore=ru* --ignore=de* --ignore=locale.alias --ignore=C --ignore=POSIX`

do rm -rf $dir

done

cd /usr/share/man

for dir in `\ls --ignore=bg* --ignore=ja* --ignore=en* --ignore=ru* --ignore=man*`

do rm -r $dir

done

popd >/dev/null 2>&1; echo "Done."

}
```

I'd like to strip out a bit more, but I don't know what I can remove and what not...

Now for the big one:

```
sysclean() {

echo -n "Running sysclean. First step: emerge --depclean\n\n\n"

sleep 5

echo -n "Running emerge --depclean...\n\n\n"

emerge --depclean -v

echo -n "\n\n\nSecond Step: revdep-rebuild\n\n\n"

sleep 5

echo -n "Running revdep-rebuild...\n\n\n"

revdep-rebuild

echo -n "\n\n\nThird Step: i18n_purge\n\n\n"

sleep 5

echo -n "Running i18n_purge...\n\n\n"

yes | i18n_purge

echo -n "\n\n\nFinal Step: eclean-dist -d\n\n\n"

sleep 5

echo -n "Running eclean-dist -d...\n\n\n"

eclean-dist -d

echo "\n\n\nDone. System has been cleaned.\n\n\n"

}
```

Bet you can't guess what that does!

The logic in the order:

Once you've run --depclean, running revdep-rebuild will (hopefully) resolve any issues before going through (and thus hopefully avoiding the hassle of a recompile) with removing locales, and the distfiles. I use i18n_purge instead of localepurge because well, it does the same thing, and does it just as well, without requiring one to run perl..

Edit: Added some additional info

----------

## Dralnu

for those who use screen with rtorrent:

run rtorrent as:

nice --adjustment=15 rtorrent

to save yourself some headaches when checking a hash.

----------

## melange

Do as the topic says, share your tips and great ideas  :Smile: 

It could be anything from an awesome script like unfoo, to something really useful shell utils like CTRL+C, bg, fg and jobs, or absolutely useless like "/usr/bin/yes" or "/usr/games/banner"

----------

## mdeininger

ctrl+s & ctrl+q

ctrl+s will freeze the console,

ctrl+q will thaw it back up.

pretty useful if you have a lot of output scroll by really fast and you need to examine something in the middle that's getting pushed outta that annoyingly small scrollback buffer too fast.

----------

## bunder

alias stuff.

 *Quote:*   

> alias duh='du -h --max-depth=1'
> 
> alias grep='grep --colour=auto'
> 
> alias h='history | tail -n 50'
> ...

 

----------

## melange

 *mdeininger wrote:*   

> ctrl+s & ctrl+q
> 
> ctrl+s will freeze the console,
> 
> ctrl+q will thaw it back up.
> ...

 

hmm. I can't get that working. Which shell are you using? (I tried with bash and zsh)

----------

## petrjanda

rm -rf / will make your penis grow bigger and your woman will not want another man in bed.

----------

## mdeininger

 *melange wrote:*   

>  *mdeininger wrote:*   ctrl+s & ctrl+q
> 
> ctrl+s will freeze the console,
> 
> ctrl+q will thaw it back up.
> ...

 it's a terminal function... works on "real" virtual terminals on tty1 and the like, and on virtual terminals like xterm... at least those're the only ones i tried it on.

EDIT: try with a script like this one:

```
while sleep 1; do echo .; done
```

----------

## PraetorZero

 *melange wrote:*   

> Do as the topic says, share your tips and great ideas 
> 
> It could be anything from an awesome script like unfoo, to something really useful shell utils like CTRL+C, bg, fg and jobs, or absolutely useless like "/usr/bin/yes" or "/usr/games/banner"

 

What does yes do?  Just do a Y and carriage return?

----------

## /dev/random

 *PraetorZero wrote:*   

>  *melange wrote:*   Do as the topic says, share your tips and great ideas 
> 
> It could be anything from an awesome script like unfoo, to something really useful shell utils like CTRL+C, bg, fg and jobs, or absolutely useless like "/usr/bin/yes" or "/usr/games/banner" 
> 
> What does yes do?  Just do a Y and carriage return?

 

It prints a string repeatedly until you kill it with ^C.

# yes foo

Would print foo to the screen until you kill it.

----------

## mdeininger

 *PraetorZero wrote:*   

>  *melange wrote:*   Do as the topic says, share your tips and great ideas 
> 
> It could be anything from an awesome script like unfoo, to something really useful shell utils like CTRL+C, bg, fg and jobs, or absolutely useless like "/usr/bin/yes" or "/usr/games/banner" 
> 
> What does yes do?  Just do a Y and carriage return?

 

y

y

y

y

y

y

y

y

y

y

y

y

y

y

y

y

y

^C

----------

## melange

 *PraetorZero wrote:*   

>  *melange wrote:*   Do as the topic says, share your tips and great ideas 
> 
> It could be anything from an awesome script like unfoo, to something really useful shell utils like CTRL+C, bg, fg and jobs, or absolutely useless like "/usr/bin/yes" or "/usr/games/banner" 
> 
> What does yes do?  Just do a Y and carriage return?

 

actually it's not *totally* useless  :Smile:  assume you have an app which asks a lot of y/N questions and you just want to say yes to all of them. Then you just do:

```

$ yes | my_app

```

----------

## arcanex

```

alias q='exit'

```

Convenient if you open and close the terminal a lot. Then, if you want to launch an X app without keeping the terminal open, you can just append '&q' to the end of the command.

```

set -o vi

```

Turns on vi mode in bash. Pretty much required if you like vi. Especially useful is the '/' command to search your command history.

If you like vi, you might like this script I use as my XClipboard manager (requires xclip):

```

#!/bin/sh

VI="vim -n"

XCLIP=/home/paulo/bin/xclip

TMPFILE=/tmp/viclip.${RANDOM}.tmp

${XCLIP} -o > ${TMPFILE}

until [ "$I" == "q" ]

do

   ${VI} ${TMPFILE}

   ${XCLIP} < ${TMPFILE}

   clear

   ${XCLIP} -o

   echo ""

   echo "===[Type 'q' to quit, 'p' to re-paste, any other key to re-edit]==="

   read I

   while [ "$I" == "p" ]

   do

      ${XCLIP} < ${TMPFILE}

      echo "==[repasted]=="   

      read I

   done

done

rm ${TMPFILE}

```

Then I bind a key to launch this script (viclip.sh). It opens up vi with the current XClipboard content, allows you to edit it, then keeps the xterm open so that you don't lose it (which is really easy), and also allows you to re-paste (to the XClipboard) or re-edit. I also like to use it as an all-purpose temporary text file editor; I wrote this post in 'viclip.sh', for example, then pasted it to the Firefox text box.

Also, instead of Ctrl-s and Ctrl-q, I prefer Ctrl-z. It halts the program execution entirely, and that's usually what I want to do (when compiling, for example.) Then I can just 'fg' back if and when I want to.

----------

## papal_authority

 *mdeininger wrote:*   

> it's a terminal function... works on "real" virtual terminals on tty1 and the like, and on virtual terminals like xterm... at least those're the only ones i tried it on.

 

Yah, it's software flow control (i.e. XON/XOFF), I generally only use it when I'm on an actual hardwired terminal. Once you have a mouse, multiple sessions, and cut n' paste, it really isn't all that useful IMHO. To each their own though  :Smile: 

----------

## mdeininger

 *papal_authority wrote:*   

>  *mdeininger wrote:*   it's a terminal function... works on "real" virtual terminals on tty1 and the like, and on virtual terminals like xterm... at least those're the only ones i tried it on. 
> 
> Yah, it's software flow control (i.e. XON/XOFF), I generally only use it when I'm on an actual hardwired terminal. Once you have a mouse, multiple sessions, and cut n' paste, it really isn't all that useful IMHO. To each their own though 

 kinda depends... when you're compiling something big or you're debugging something with a lot of logfile output, and your terminal's scrollback buffer is a bit short, ctrl+s is pretty handy  :Smile: .

it's handy to know either way; it also seems to be one of those lesser-known bits, and it's somewhat console-related, so i figured i'd throw it in =)

----------

## poly_poly-man

^d is your friend  :Wink: 

Also, shift Page up/down is good, and (ctrl-)alt-Fx

also, the best command ever:

telnet polypmanports.hopto.org

poly-p man

----------

## denstark

 *poly_poly-man wrote:*   

> ^d is your friend 
> 
> Also, shift Page up/down is good, and (ctrl-)alt-Fx
> 
> also, the best command ever:
> ...

 

that wasn't a plug at ALL.

----------

## poly_poly-man

 *denstark wrote:*   

>  *poly_poly-man wrote:*   ^d is your friend 
> 
> Also, shift Page up/down is good, and (ctrl-)alt-Fx
> 
> also, the best command ever:
> ...

 

Just a simple command that works on many systems  :Very Happy: 

poly-p man

----------

## Bones McCracker

Repeat the last command, replacing string1 with string2

```
^string1^string2^
```

By the way, there's a thread in the Tips & Tricks forum on the exact same topic that has accumulated five years worth of tips:

https://forums.gentoo.org/viewtopic-t-15443-highlight-shell.html

----------

## Etal

 *mdeininger wrote:*   

>  *papal_authority wrote:*    *mdeininger wrote:*   it's a terminal function... works on "real" virtual terminals on tty1 and the like, and on virtual terminals like xterm... at least those're the only ones i tried it on. 
> 
> Yah, it's software flow control (i.e. XON/XOFF), I generally only use it when I'm on an actual hardwired terminal. Once you have a mouse, multiple sessions, and cut n' paste, it really isn't all that useful IMHO. To each their own though  kinda depends... when you're compiling something big or you're debugging something with a lot of logfile output, and your terminal's scrollback buffer is a bit short, ctrl+s is pretty handy .
> 
> it's handy to know either way; it also seems to be one of those lesser-known bits, and it's somewhat console-related, so i figured i'd throw it in =)

 

I prefer ScrollLock

----------

## Bones McCracker

More of a console tip than a shell tip:

Command history incremental search (as a key combo).

1.  Type first few chars of some command in your history you'd like to repeat

2.  press 'Meta+PgUp'     

This retrieves the most recent matching command (right one? hit return to execute; not right? press it again and incremental search continues).

The modifier key varies depending on how your /etc/inputrc is set up and what you are using (tty, gnome-terminal, konsole, etc.)

I have found this to be very handy.  You'll be surprised how much of your terminal work is the same commands used over and over.   There are other related key combinations (explore inputrc and man bash), but that's the one I've found the most useful.

----------

## bunder

 *BoneKracker wrote:*   

> By the way, there's a thread in the Tips & Tricks forum on the exact same topic that has accumulated five years worth of tips:
> 
> https://forums.gentoo.org/viewtopic-t-15443-highlight-shell.html

 

merged.   :Wink: 

----------

## bunder

want to look for bots who tried logging into your ssh/ftp servers in the past day?

```
grep "`date +'%b %e'`" /var/log/auth.log | grep "Invalid user"

grep "`date +'%b %e'`" /var/log/vsftpd.log | grep "FAIL LOGIN"

```

works great in cron.   :Wink: 

----------

## JeliJami

 *BoneKracker wrote:*   

> More of a console tip than a shell tip:
> 
> Command history incremental search (as a key combo).
> 
> 1.  Type first few chars of some command in your history you'd like to repeat
> ...

 

Cool, but I like Ctl-R better

1. Type Ctl-R (prompt changes)

2. Type some chars of a former command (does not need to be the first ones)

3. Use backspace to correct errors

----------

## Bones McCracker

 *davjel wrote:*   

>  *BoneKracker wrote:*   More of a console tip than a shell tip:
> 
> Command history incremental search (as a key combo).
> 
> 1.  Type first few chars of some command in your history you'd like to repeat
> ...

 

Cool.  I didn't know about that.  I like that better too!    :Very Happy: 

----------

## swimmer

Hmm - is this shell-dependent? If I use Ctrl-R in zsh nothing happens ...

Greetz

swimmer

----------

## JeliJami

 *swimmer wrote:*   

> Hmm - is this shell-dependent? If I use Ctrl-R in zsh nothing happens ...

 

/me using bash

----------

## Bones McCracker

zsh must have command history incremental search -- it's probably a different key binding or something.  Look at info zsh or something.  On bash these sorts of things are set up in inputrc.

----------

## swimmer

Hmm - 'pinfo zsh' mentions indeed Ctrl-R for incremental history search backwards but using this keybinding nothing happens whereas it works as designed in bash :-/

But hey - I started using zsh recently and am still an absolut n00b in his usage  :Wink: 

Thanks anyway

swimmer

----------

## Bones McCracker

I really hate to say it, but ....  you could always, uh ...  RTFM.     :Razz: 

----------

## Ox-

 *swimmer wrote:*   

> Hmm - 'pinfo zsh' mentions indeed Ctrl-R for incremental history search backwards but using this keybinding nothing happens whereas it works as designed in bash :-/
> 
> But hey - I started using zsh recently and am still an absolut n00b in his usage 
> 
> Thanks anyway
> ...

 Going off the top of my head here so I could be wrong, but ctrl-R for history search is usually the key binding in "emacs mode".  If you shell editing mode is something else like vi then binding will be different.  It's been 16-years since I last used zsh and it's not installed on my box so I can't look up the stuff in zsh.1 for you  :Smile: 

----------

## ppurka

duh!

```
echo "bindkey \"^R\"                history-incremental-search-backward

bindkey \"^S\"                history-incremental-search-forward" >> .zshrc

. .zshrc
```

----------

## Bones McCracker

 *ppurka wrote:*   

> duh!

 

http://www.amazon.com/How-Win-Friends-Influence-People/dp/0671723650

----------

## ppurka

 *BoneKracker wrote:*   

>  *ppurka wrote:*   duh! 
> 
> http://www.amazon.com/How-Win-Friends-Influence-People/dp/0671723650

 eww! Who reads all that   :Rolling Eyes: 

----------

## Bones McCracker

 *ppurka wrote:*   

>  *BoneKracker wrote:*    *ppurka wrote:*   duh! 
> 
> http://www.amazon.com/How-Win-Friends-Influence-People/dp/0671723650 eww! Who reads all that  

 

People who used to say "duh!" when offering someone a tip?    :Smile: 

----------

## swimmer

 *ppurka wrote:*   

> duh!
> 
> ```
> echo "bindkey \"^R\"                history-incremental-search-backward
> 
> ...

 

Luckily I don't know what "duh!" means and I think I don't want to know  :Wink: 

Thanks for the tip ppurka  :Smile: 

----------

## Alanceil

Why didn't I find this thread earlier ? *beats himself*

There were some really nice gems in here. ( Feels like "You just gained a level in Bash Magic!" )

In return, part of my bash config:

```

shopt -s cdspell

shopt -u extdebug

complete -d cd

complete -c which

complete -c man

complete -c killall

alias ..='cd ..'

alias ...='cd ../..'

alias ....='cd ../../..'

alias .....='cd ../../../..'

alias l='ls -lF --color=always'

alias la='ls -la --color=always'

alias lh='ls -lh --color=always'

alias ll='ls -l --color=always'

alias ls='ls --color=always'

alias lS='ls -lS'

alias c='cd'

alias o='/usr/bin/less'

alias vo='/usr/bin/vim'

alias bi='/usr/bin/vim'

alias vu='/usr/bin/vim'

alias suvi='sudo /usr/bin/vim'

alias xc='/usr/bin/xv'

PS1='\[\033[0;32m\]\u@\h\[\033[0m\]:\[\033[0;36m\]\A\[\033[0m\]:\[\033[1;30m\]${?}\[\033[0m\]:\[\033[1;34m\]\w\[\033[0m\]>\[\033[0m\] '

```

I sometimes hit the wrong keys when I want to start vi, so there are some aliases to catch that. (In case you ask)

----------

## ppurka

 *Alanceil wrote:*   

> I sometimes hit the wrong keys when I want to start vi, so there are some aliases to catch that. (In case you ask)

 I believe there is some shell setting which makes the shell suggest you the correct alternative if you had a typo in the previous command.

----------

## purpler

oh yes, that setting is called ZSH  :Smile: 

/etc/zsh/zshrc:

setopt correctall

----------

## Alanceil

Then I'll still have to use my vi aliases  :Wink: 

I tried zsh several times, and never liked it.

... and sth. for the topic:

```
function path(){

        test -e "$1" && echo "`pwd`/${1}"

}
```

----------

## Dralnu

 *purpler wrote:*   

> oh yes, that setting is called ZSH 
> 
> /etc/zsh/zshrc:
> 
> setopt correctall

 

bash has a similar feature.

----------

## arcanex

BashFAQ

http://wooledge.org:8000/BashFAQ

BashPitfalls

http://wooledge.org:8000/BashPitfalls

Between them, just about everything you might ever want to know about BASH.

----------

## MartyParish

Hey, here's a list that contains plenty of stuff that's been mentioned already but some stuff that I did not see. I read the whole thread too! It was great.

Ctrl + A - Go to the beginning of the line you are currently typing on

Ctrl + E - Go to the end of the line you are currently typing on

Ctrl + L - Clears the Screen, similar to the clear command

Ctrl + U - Clears the line before the cursor position. If you are at the end of the line, clears the entire line.

Ctrl + H - Same as backspace

Ctrl + R - Let’s you search through previously used commands

Ctrl + C - Kill whatever you are running

Ctrl + D - Exit the current shell

Ctrl + Z - Puts whatever you are running into a suspended background process. fg restores it.

Ctrl + W - Delete the word before the cursor

Ctrl + K - Clear the line after the cursor

Ctrl + T - Swap the last two characters before the cursor

Esc + T - Swap the last two words before the cursor

Alt + F - Move cursor forward one word on the current line

Alt + B - Move cursor backward one word on the current line

Tab - Auto-complete files and folder names

Ctrl + W - erase word before cursor

Ctrl + Y - to paste it (as in delete and copy) all text in front of the cursor

Esc + . (or Esc + Underscore) - Insert Last Argument 

Ctrl + b - Move back a character

Ctrl + f - Move forward a character

Ctrl + r - Search the history backwards

Ctrl + xx - Move between EOL and current cursor position

Ctrl + x @ - Show possible hostname completions

Alt + < - Move to the first line in the history

Alt + > - Move to the last line in the history

Alt + ? - Show current completion list

Alt + * - Insert all possible completions

Alt + / - Attempt to complete filename

Alt + . - Yank last argument to previous command

Alt + c - Capitalize the word

Alt + d - Delete word

Alt + l - Make word lowercase

Alt + n - Search the history forwards non-incremental

Alt + p - Search the history backwards non-incremental

Alt + r - Recall command

Alt + t - Move words around

Alt + u - Make word uppercase

Alt + back-space - Delete backward from cursor

Here "2T" means Press TAB twice

$ 2T - All available commands(common)

$ (string) 2T - All available commands starting with (string)

$ /2T - Entire directory structure including Hidden one

$ 2T - Only Sub Dirs inside including Hidden one

$ *2T - Only Sub Dirs inside without Hidden one 

$ ~2T - All Present Users on system from "/etc/passwd"

$ $2T - All Sys variables

$ @2T - Entries from "/etc/hosts"

$ =2T - Output like ls or dir

----------

## devsk

put this in your ~/.bashrc if you just want to override part of the DIR_COLORS and don't want to copy the full file to ~/.dir_colors and maintain it in future if /etc/DIR_COLORS changes:

```
eval `cat /etc/DIR_COLORS ~/.dir_colors | dircolors -
```

----------

## David Serrano

Great thread!!

 *tam1138 wrote:*   

> Also, using the ":p" option on any potentially-dangerous bash replacement tricks is useful: it prints out the command that WOULD be run and also appends it to your history.  That is, if you think you want to run the last command starting with 'r' in your history but don't want to hose yourself before verifying the command:
> 
> ```
> $ !r:p
> 
> ...

 

I use:

```
shopt -s histverify
```

With this, you get confirmation for all history expansions. That's useful not only for verifying potentially harmful 'rm' commands, but also to change some parameters, files and whatever before actually running the command.

Here are my aliases and functions:

```
function del() {

  /bin/mv -f "$@" $HOME/.trash/;

}

alias cd='cd -P'

alias ls='ls -F -N --color=tty --time-style="+%Y%m%d:%H%M%S%z"'

alias ll='ls -l'

alias cl='clear; logout'

alias cv='clear; vlock -a'

alias lless='ll -R --color=always | less -r'

## allows 'h emerge -s' without quoting the space

function h() { HISTTIMEFORMAT= history | grep "$*"; }

alias ltrace='ltrace -S -tt -C'

alias strace='strace -s 500 -tt -ff'

alias vim='vim -X -o'

alias bc='bc ~/.bcrc'  ## set up default number of decimals, .bcrc contains "scale=4"

alias perl='perl -Mstrict -w'

alias pf='perldoc -f'

alias pd='perldoc'

alias pq='perldoc -q'

alias xev='xev | grep keycode'

function rmoz() {

    ## ripped from      https://bugzilla.mozilla.org/attachment.cgi?id=151958

    ## which appears in https://bugzilla.mozilla.org/show_bug.cgi?id=246168

    if [ "$1" ]; then 

        if [ -f "$PWD/$1" ]; then

            LOCAL="file://$PWD/$1"

        elif [ -f "$1" ]; then 

            LOCAL="file://$1"

        else 

            LOCAL="$1"

            [[ $LOCAL =~ ^http:// ]] || LOCAL="http://$LOCAL"

        fi

        DISPLAY=:0 mozilla -remote "openurl($LOCAL,new-tab)"

    fi

}

## show version of specified perl modules

function pmver() { perl -le "eval { require ${1} } and print qq{${1}: },\$${1}::VERSION or print qq{${1}: none}"; }

function ls-() { ls -"$@"; }
```

Environment variables:

```
export HISTCONTROL=ignoredups:erasedups

export HISTIGNORE="date:df:fg:jd:jobs:ll:ls"

export HISTTIMEFORMAT="%Y%m%d:%H%M%S%z"

export IGNOREEOF=1

export LESS='-c -h1 -y1 -j2 -S'

export LESS="$LESS -P B%bt-%bB?B/%B.?pt(%pt\%). ?ltL%lt-%lb.?L/%L.?Pt(%Pt\%). .?f%f:-.?e (END).?m (file %i of %m).%t"

unset LESSOPEN  ## hate this

## use with 'ps -eH' or 'ps -e f'

export PS_FORMAT="pid,pgid,euid,egid,nlwp:2=NT,ni:2,rtprio:2=RT,cls:2,vsz:6,rss:6,pcpu,pmem,stat:3=ST,tname:6,stime,bsdtime,args"

export TIMEFORMAT=$'\nreal: %3R, user: %3U, sys: %S'

export TMPDIR=~/tmp

export TMP=$TMPDIR

unset PERL5LIB;

DIRS=(~/em/perl-modules/{lib,share}/perl/*);

local IFS=":";

export PERL5LIB="${DIRS[*]}";
```

Misc:

```
shopt -s cdable_vars checkhash checkwinsize cmdhist extquote histappend histreedit histverify

shopt -u force_fignore

if [[ "`tty`" =~ ^/dev/tty ]]; then  ## things for console only

  setterm -blength 10 -bfreq 10000   ## barely hearable, prevents waking up people

fi
```

.inputrc:

```
set horizontal-scroll-mode off

## 'audible' or 'visible'

set bell-style audible

set meta-flag on

set input-meta on

set output-meta on

set convert-meta off

set history-preserve-point on

set editing-mode vi-command

set keymap vi-command

set page-completions off

set visible-stats on

## todo: yank-nth-arg

## todo: yank-last-arg
```

.xbindkeysrc:

```
"xkbcomp /home/hue/.hue-xkb/es-qwerty-hue :0"

  control+F1

"xkbcomp /home/hue/.hue-xkb/es-dvorak-hue :0"

  control+F2

"xwd -root -silent | convert xwd:- png:/home/hue/xwd-$(date +%Y%m%d:%H%M%S.png)"

 Print
```

The ~/.hue-xkb files were generated by using xkbcomp; then further tweaked. It's like using xmodmap.

Last, I'd like to bump this excellent tip (not for obtaining the IP, but for its use of 'set'):

 *dub.wav wrote:*   

> 
> 
> ```
> alias currentip='set `/sbin/ifconfig eth0` && echo ${7#*:}'
> ```
> ...

 

----------

## faux

Nice thread. Read the whole one, really useful!

Job Management

```
%<job ID>
```

 recalls a running or suspended job.

```
jobs
```

 lists jobs of current session.

Ctrl+Z suspends current job and sends it to background.

```
<command> &
```

 starts a job in backgroud.

screen usage in my .bashrc

```
if [ $SHLVL -eq 1 ]; then

  /usr/bin/screen -xRR

fi
```

Resumes the last screen session (or starts a new one, if nothing to resume) if using an tty (not a terminal like xterm) or SSH session. Very useful on SSH sessions if connection times out.

view ebuild of package

```
eview() {

        FILE=$(equery which $1)

        if [ -f "$FILE" ]; then

                view $FILE

        fi

}
```

----------

## notHerbert

It has happened that I mistyped an append command in an important file. 

My desire is to do something like this

```
echo "some configuration" >> /etc/somefile
```

 But instead I type

```
echo "some configuration" > /etc/somefile
```

Consider

```
# echo "something something" > /etc/passwd
```

This command would overwrite /etc/passwd, and would be a real pain to repair - even if the error is caught before logging out.  

If I add this to .bashrc (then source .bashrc)

```
set -o noclobber
```

Then I can do this

```
# echo "a bunch of crap" > /etc/passwd

-su: /etc/passwd: cannot overwrite existing file
```

Now I caught my typo before making a mess. 

Now if my intention really is to overwrite a file, a pipe character will allow me to do that.  

To clear the contents of $HOME/.xsession-errors, type

```
$ :>| $HOME/.xsession-errors
```

----------

## a.b.

The only interesting things in my .zshrc are:

```
# With -p, Paludis should have normal niceness

# Else, it should be extremly friendly

function paludis(){

    if echo $@ | egrep '\-.*p\ ' > /dev/null; then

        /usr/bin/paludis $@

    else

        nice -n19 /usr/bin/paludis $@

    fi

}
```

and

```
# For the really bullish processes

function murder(){

    while [[ $? = 0 ]]; do

        kill -9 $@

    done

}
```

The rest:

http://shellium.org/~aeebee/dotfiles/zshrc

----------

## a.b.

 *notHerbert wrote:*   

> It has happened that I mistyped an append command in an important file. 

 

That has happened to me several times as well. Backups more or less solve that  :Wink: 

----------

## notHerbert

A bash command prompt that prints the return value in the prompt if it is not equal to zero.   :Smile: 

```
PS1='\w \u$(r=$?; test $r -ne 0 && echo " \[\e[1;31m\]ret:$r")\e[0m\] \$ '
```

----------

## mv

 *notHerbert wrote:*   

> A bash command prompt that prints the return value in the prompt

 

This is once more an example why it is wiser to use zsh as the interactive shell. There you can just include %? or (for analogous behaviour to your case) %(?||ret:%?) within PS1 (coloring omitted for simplicity). Or even simpler and IMHO more convenient for daily usage: setopt print_exit_value.

----------

## Dralnu

renice <nice_value> `pgrep <proccess to renice>`

Or

renice <nice_val> $(pgrep <proc>) if you don't want the folks in #bash to yell at you

----------

## a.b.

```
function wi() { vi $(equery which $@) 
```

```
function usegrep() { grep $@ /var/repos/*/profiles/use.* }
```

and a couple of functions like

```
function bugz() { if [[ $1 == get ]]; then =bugz $@ | less; else =bugz $@; fi }
```

----------

## Dralnu

 *a.b. wrote:*   

> 
> 
> ```
> function usegrep() { grep $@ /var/repos/*/profiles/use.* }
> ```
> ...

 

I don't have a var/repos dir on my system. Are you talking about /usr/portage/profiles/use.desc?

----------

## a.b.

 *Dralnu wrote:*   

>  *a.b. wrote:*   
> 
> ```
> function usegrep() { grep $@ /var/repos/*/profiles/use.* }
> ```
> ...

 

I've put the stuff in more logical places:

```
# Folders

REPODIR="/var/repos"

PORTDIR="$REPODIR/gentoo"

PORTDIR_OVERLAY="$REPODIR/local $REPODIR/imported"

source "/var/repos/.layman/make.conf"

DISTDIR="/var/cache/distfiles"
```

In the default setup it's of course /usr/portage/etc..

----------

## Ormaaj

deletemeLast edited by Ormaaj on Wed Oct 20, 2010 3:49 am; edited 2 times in total

----------

## loudmax

Here's my prompt string:

```
PS1='\[\033[01;32m\]\u@\[\033[01;31m\]\h[\w]:`if [[ $? != 0 ]]; then echo "( "; else echo ") "; fi`\[\033[00m\]'
```

If the previous command succeeds it shows me it's happy:

```
user@host[~]:) /bin/true 

user@host[~]:)
```

If the previous command fails, it's sad

```
user@host[~]:) /bin/false

user@host[~]:( 
```

----------

## nendzd

^^^^  That is great!

Unfortunately I don't have any tips and tricks to post, although I am getting a lot of use out of this thread, thanks!

----------

## coolsnowmen

 *loudmax wrote:*   

> Here's my prompt string:
> 
> ```
> PS1='\[\033[01;32m\]\u@\[\033[01;31m\]\h[\w]:`if [[ $? != 0 ]]; then echo "( "; else echo ") "; fi`\[\033[00m\]'
> ```
> ...

 

HAHAHAHAHHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA

edit: my most recent alias -

```

alias ghistory="history | grep"

alias gh="ghistory"

```

----------

## CypherPipe

```
function ta ()

# `type -a` with more info about what "/path/file" is.

# $ ta {,z,lz}cat

# cat is /bin/cat : ELF 32-bit LSB executable

# zcat is /bin/zcat : POSIX shell script text executable

# lzcat is /usr/bin/lzcat : symbolic link to `lzma'

{

    local IFS=$'\x0A' # \n

    regex=$(eval echo -e '\(/[[:graph:]]*\)[^\\x3b\\x27\\x22]$')

#                                               ;    '    "

    for line in $(type -a "$@");

    do

        if [[ $line =~ $regex ]]; then

            tmi=$(file $BASH_REMATCH);

            trimed=${tmi%%,*};

            echo ${line%%/*}${trimed/:/ :};

        else

            echo $line;

        fi;

    done

}
```

----------

## ceric35

Bash, redefine cd : 

```
cd() {

  builtin cd $*

  ls -l

}
```

----------

## skellr

I was looking for a thread titled "post your stupid scripts", or something to that effect, but can't seem to find it. Maybe this one will work.   :Wink: 

I wanted something to help choose a foreground color against a chosen background color.

```
#!/bin/bash

if ! { data=$(showrgb); } &> /dev/null

then for x in                        \

   /etc/X11/rgb.txt             \

   /usr/lib/X11/rgb.txt         \

   /usr/share/X11/rgb.txt       \

   /usr/X11R6/lib/X11/rgb.txt   \

   /usr/openwin/lib/X11/rgb.txt \

   /usr/share/doc/python*/examples/Tools/pynche/X/rgb.txt

do

    if [[ -r $x ]]; then

   data=$(sed '/^!/d' < $x)

   break

    fi

done

fi

[[ -z "$data" ]] && { echo "Can't find \`showrgb\` or rgb.txt"; exit; }

while getopts "hub: c: f: o:" option

do

    case "$option" in

   b|c) bgcolor=$OPTARG;;

   o|f) exec > $OPTARG;;

   \?|h|u) cat <<-Hdoc

   Usage: ${0##*/} [-b color] [-o file] || ${0##*/} [-c color] [-f file]

          -b or -c   Specify a background color.

             -b \#000 | -b \#000000 | -b black | -b 'rgb(0,0,0)'

          -o or -f   Write output to file.

      Hdoc

       exit 1;;

    esac

done

declare -i r g b

sample="The quick brown fox jumps over the lazy dogs back."

fill='&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'

cat <<Hdoc

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.1 Strict//EN">

<html>

 <head>

  <title>rgb.txt Colors</title>

  <style type="text/css">

   body { background-color: ${bgcolor:-none} }

   ul   { list-style-type: none; padding-left: 1% }

   span { border: thin inset }

   pre  { display: inline }

  </style>

 </head>

 <body>

  <ul>

Hdoc

while read r g b name

do

    printf -v hex "\x23%02x%02x%02x" $r $g $b

    printf '   <li style="color: %s">\n' $hex

    printf '    <span style="background-color: %s">%s</span>\n' $hex $fill

    printf '    <pre> %s  %-23s</pre>%s\n' $hex "$name" "$sample"

    printf '   </li>\n'

done <<< "$data"

cat <<Hdoc

  </ul>

 </body>

</html>

Hdoc
```

edit: output is html

----------

## muhsinzubeir

```
#dvd to flv

alias dvd-to-flv='mplayer dvd://1 -dumpstream -dumpfile video.vob && ffmpeg -i video.vob -vcodec flv -b 1024kb -acodec libmp3lame -ar 22050 -pass 1 -f flv video.flv && ffmpeg -i video.vob -vcodec flv -b 1024kb -acodec libmp3lame -ar 22050 -pass 2 -f flv video.flv'

#avi to flv

alias avi-to-flv='ffmpeg -i video.avi -ar 44100 -ab 64k -b 400k -f flv -s 320x240 video.flv'

#wav to mp3

alias wav-to-mp3='ffmpeg -i filename.wav -acodec libmp3lame -ab 160k -ac 2 -ar 44100 filename.mp3'
```

Finally...  :Razz: 

----------

## ocin

Using ZSH.

Set READNULLCMD to cat:

```
READNULLCMD="cat"
```

for using

```
$ < file
```

instead of

```
$ cat file
```

which is quite cool with aliases like

```

alias -g G='|grep'

alias -g H='|head'

alias -g L='|less'

alias -g M='|more'

alias -g N='&>/dev/null'

alias -g P='|curl -F "sprunge=<-" http://sprunge.us'

alias -g S='|sort'

alias -g T='|tail'

alias -g W='|wc -l'

alias -g X='|xargs'

```

Examples:

This will cat file, grep for string and nopaste the result at sprunge:

```
$ < file G string P
```

Or instead of doing:

```
$ grep string file
```

use:

```
$ < file G string
```

For me this is more comfortable/logical (also it's making "useless cat" useful again :D)

Auto-attach screen when connecting to a remote linux server, for example useful if you run a screened irssi on it or just wanna auto-attach your working screen:

```

if [[ $HOST = "yourhostname" ]]; then

   [[ ! -z $(screen -list | grep nameofscreen | grep Detached) ]] && screen -aADRS nameofscreen

fi

```

Completion for a specific command:

```
compctl -g '*.ebuild' ebuild

compctl -g '*.torrent' hrktorrent

```

For example you type

```
$ hrktorrent <TAB>
```

and it will only list all files ending with .torrent and folders of course

TAB/Arrow-Key driven kill menu:

```
zstyle ':completion:*:kill:*' force-list always

zstyle ':completion:*:processes' insert-ids

if [[ $UID = "0" ]]; then

        zstyle ':completion:*:processes' command 'ps axf -o pid,%cpu,%mem,tty,cputime,cmd | sed /ps/d | grep -vE "sed|grep"'

else

        zstyle ':completion:*:processes' command 'ps f -u $USER -o pid,%cpu,%mem,tty,cputime,cmd | sed /ps/d | grep -vE "sed|grep"'

fi

zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#)*=0=01;31'

```

Strip comments and blank lines out of a file:

```
alias confcat='grep -vE "^#|^$"'
```

Easy scp (in this example "foo" is a hostname configured in ~/.ssh/config)

```
cp2web() { scp $* foo:public_html }
```

Check for window properties, useful with windows managers where you need them or tools like devilspie:

```
propstrings() { xprop | grep -E '^(WM_NAME)|(WM_WINDOW_ROLE)|(WM_CLASS)' }
```

Easy ssh unkey:

```
unkey_host() {

   if [[ ! $# -eq 1 ]]; then

      echo "usage: unkey_host <hostname>"

   else

      sed -i -e "/$1/d" $HOME/.ssh/known_hosts

   fi

}

```

Finally my gentoo specific aliases:

```
if [[ $HOST = "hostname" && $UID = "0" ]]; then

   alias kmake='make -j3 && make install && make modules_install'

   alias python-updater='python-updater -P paludis'

   alias srcenv='env-update && source /etc/zsh/zprofile && source ~/.zshrc'

   alias uninstall-unused='paludis --uninstall-unused && reconcilio'

   alias vipk='vim /etc/paludis/keywords.conf'

   alias vipo='vim /etc/paludis/use.conf'

   alias vipu='vim /etc/paludis/package_unmask.conf'

   alias vipm='vim /etc/paludis/package_mask.conf'

   alias vipb='vim /etc/paludis/bashrc'

fi

```

----------

## truc

 *ocin wrote:*   

> Using ZSH.
> 
> Set READNULLCMD to cat:
> 
> ```
> ...

 

I don't really know zsh, but I'm 99% sure you don't need to set READNULLCMD=cat to use do that,  "<file" is just the same as telling stdin = read from "file" and grep, as well as other, can use standard input, and that's even what's happening the way you're calling it (cat file | grep blah).

I still see a useless cat here;)

Try this:

```
alias G=grep
```

then

```
<file G blah
```

And btw, since I like 'ed' here is my delKnownHost function

```
delKnownHost () 

{ 

    [ -z "$1" ] && { 

        echo "delKnownHost number";

        return 1

    };

    ed -s ~/.ssh/known_hosts  <<EOT

H

${1}d

wq

EOT

}
```

----------

## truc

whereas you're a tmux user or a screen one, it's so easy to start a new shell in a split window(well it's easier with tmux..) just to check a few things that I tend to do it like all the time... One thing which used to annoy me when doing this is the time spent loading bash completion.

Since I usually don't need it for the few first commands I run in this split window, I decided I could delay a little this loading.

By delaying it a little I mean, not loading it before the first prompt, but later, I chose to load them after the third command.

If you're also that impatient, add this to your .bashrc

```
# sourcing /etc/bash_completion takes some time, try to delay it a little

_MYCMDNB=0

my_prompt_command() {

   _MYCMDNB=$((_MYCMDNB+1))

   if [ $_MYCMDNB -gt 3 ]; then

      [ -f /etc/bash_completion ] && source /etc/bash_completion

      unset PROMPT_COMMAND

      unset _MYCMDNB

      unset my_prompt_command

   fi

}

PROMPT_COMMAND=my_prompt_command

```

Of course, you'll have to adapt it if you already use the PROMPT_COMMAND for something.

----------

## rldawson

Place your $HOME/bin in $PATH:

```
[ -d $HOME/bin ] && { PATH=$PATH:$HOME/bin;export PATH; }
```

----------

## SlashBeast

$HOME/bin should be first in PATH so it will be choosen over system's bin dirs.

from my zshrc

```
if ! [[ "${PATH}" =~ "^${HOME}/bin" ]]; then

        export PATH="${HOME}/bin:${PATH}"

fi
```

----------

## rldawson

On my rigs I prefer to allow the system to have first call and then $HOME, but I like your code sample.   :Very Happy: 

----------

## rldawson

alias this command to hash your directories:

```
sha=sha512sums-${PWD##*/};[ -f $sha ] && rm $sha;find . -type f -exec sha512sum {} \; > /tmp/$sha;mv /tmp/$sha .
```

----------

## Ormaaj

Print today's merges:

Bash (requires version >= 4.2):

```
f(){ [[ -n "${1%%"${1##"$2"}"}" ]] && echo "${1#*>>> }"; }; qlop -Cl | tail -n 1000 | while read -r; do f "$REPLY" "$(printf '%(%a %b %d)T' -1)"; done
```

Awk:

```
qlop -Cl | tail -n 1000 | gawk -F '>>>[[:space:]]*' '{split($0,a,/[[:space:]]+/)} strftime("%a %b %d",systime()) == a[1]" "a[2]" "a[3] {print $2}'
```

----------

## katfish

might be useful for you too... 

alias c='clear'

alias ls='ls --color'

alias l='ls -lah --color'

alias df='df -h'

alias du='du -h'

alias ..='cd ..'

alias loc='locate'

alias k9='kill -9 '

alias psg='ps aux | grep '

alias e='emerge'

alias ew='e world -uDNv --keep-going'

alias es='layman -S;eix-sync'

alias ewa='e world -uDNtav --keep-going'

alias edc='e --depclean -av'

alias dpc='dispatch-conf'

alias grep='grep --color=auto'

alias fgrep='fgrep --color=auto'

alias egrep='egrep --color=auto'

export HISTCONTROL=erasedups

export HISTSIZE=1000000

shopt -s histappend

shopt -s checkwinsize

----------

## tomk

Merged previous post.

----------

## prometheanfire

my update vcs-sync script (to update all my repos and stuff and put me back where I started)

```
vcs-sync() {

   pushd /home/mthode/gentoo-x86

   cvs up

   echo "/home/mthode/hardened-dev"

   cd /home/mthode/hardened-dev

   git pull

   echo "/home/mthode/sunrise"

   cd /home/mthode/sunrise

   svn up

   echo "/home/mthode/prometheanfire"

   cd /home/mthode/prometheanfire

   git pull

   popd

}
```

I also have a couple of other random and obvious things.

```
alias           ~='cd ~'

alias           ..='cd ..'

alias           ...='cd ../..'

alias           ....='cd ../../..'

alias           .....='cd ../../../..'

alias           rm="rm -i"

alias      ls="ls -G"

alias           ssh="ssh -A -o VisualHostKey=yes"

alias           webshare='python -c "import SimpleHTTPServer;SimpleHTTPServer.test()"'

alias           pgrep='pgrep -lf'

complete        -cf sudo

```

----------

## krizz

 *mthode wrote:*   

> I also have a couple of other random and obvious things.
> 
> ```
> alias           ~='cd ~'
> ```
> ...

 

You can just do..

```
cd
```

..to go back to your home directory as well, no need for an alias I'd say.

----------

## ppurka

 *krizz wrote:*   

>  *mthode wrote:*   I also have a couple of other random and obvious things.
> 
> ```
> alias           ~='cd ~'
> ```
> ...

 In fact many of those bindings come for free with zsh.

```
setopt autocd
```

This will make .. work and take you to parent directory. Also ~ by itself will take you to home directory.

Also, I wonder why ..... etc are so "popular"? Why not an alias .3, .4 and .5 to go up 3, 4, or 5 directories respectively?

----------

## slick

Set the time via internet with bash only:

```
date -u '+%y-%m-%d %H:%M:%S' -s "$(cat </dev/tcp/time.nist.gov/13|cut -d ' ' -f2,3)" 
```

----------

## khayyam

 *ppurka wrote:*   

> Also, I wonder why ..... etc are so "popular"? Why not an alias .3, .4 and .5 to go up 3, 4, or 5 directories respectively?

 

ppurka ... well, I use the former for 'cd' and the latter as 'global' ('-g') aliases just to denote the path, I also have alias 2=' cd +2', etc, which just adds to the smorgasbord of options :)

I do this as I'm lazy, mostly ... but also because I might use them in different ways.

```
# pwd

/home/khayyam/foo/ba/src

# mv foo .2 ; 2

# pwd

/home/khayyam/foo

# 1 ; pwd

/home/khayyam/foo/ba/src

# .. ; pwd

/home/khayyam/foo/ba
```

The '..' aliases I use mainly because its just a matter of hitting the period key a couple of times ... did I mention I'm lazy? :) I also use 'push/popd +|-' (which I have aliased to 'pu' and 'po') so ... various methods of achieving the same results.

best ... khay

----------

## khayyam

 *SlashBeast wrote:*   

> $HOME/bin should be first in PATH so it will be choosen over system's bin dirs.
> 
> from my zshrc
> 
> ```
> ...

 

SlashBeast ... this isn't necessary with zsh as it has a 'path' array (lowercase) ... the array is cleared of any duplicates and used to provide $PATH. You can also use a 'glob qualifier' to ignore if the directory doesn't exist.

~/.zprofile

```
typeset -U path

export path

 

path=($HOME/bin(N-/) $path)
```

best ... khay

----------

## JohnBlbec

 *Dizzutch wrote:*   

> a sequence of BASH commands that I like to use is the following:
> 
> ```
> for i in *; do [ -d $i ] && du -sh $i; done
> ```
> ...

 

shorter:

```
for d in */; do du -sh "$d"; done
```

----------

## khayyam

 *JohnBlbec wrote:*   

>  *Dizzutch wrote:*   
> 
> ```
> for i in *; do [ -d $i ] && du -sh $i; done
> ```
> ...

 

John ... shorter still:

```
% echo $SHELL

/bin/zsh

% du -sh *(/)
```

... sorry, no "glob qualifiers" for you dear bash user ;)

best ... khay

----------

## JohnBlbec

I haven't noticed it is about zsh, sorry. it works in bash and I haven't tried it in sh yet.

----------

## khayyam

 *JohnBlbec wrote:*   

> I haven't noticed it is about zsh, sorry. it works in bash and I haven't tried it in sh yet.

 

John ... it isn't, the thread is "shell tips & tricks", so not shell specific ... I simply added the above because it was "shorter" than the provided bash ... and for interactive use zsh provides much in that regard. Seeing as a loop was used I could have provided the following, rather than "glob qualifiers".

```
% setopt short_loops

% for ((i=1; i<4; i++)) echo "count to $i"

count to 1

count to 2

count to 3
```

... or, perhaps more useful

```
% i=1; for f (*(.)) {mv $f $i.$f ; ((i++))}
```

... and with the 'glob qualifier' I could make the target of the loop more selective, ie based on modification time, file permissions, filetype, uid, guid, filesize, etc, etc. Also, qualifiers can be negated, and used in combination.

The same 'short_loop' can be used for other loops, eg 'while'

```
% while (true) {echo hello ; sleep 3}
```

So, there you have it ... "shorter".

best ... khay

----------

## JohnBlbec

 *khayyam wrote:*   

>  *JohnBlbec wrote:*    *Dizzutch wrote:*   
> 
> ```
> for i in *; do [ -d $i ] && du -sh $i; done
> ```
> ...

 

```
$ echo $SHELL

/bin/bash

$ du -sh */
```

:-)

----------

## khayyam

 *JohnBlbec wrote:*   

>  *khayyam wrote:*   
> 
> ```
> % echo $SHELL
> 
> ...

 

JohnBlbec ... which, as far as I know, is the only bash glob qualifier ... whereas zsh offers:

#  -- introduce glob flag

%  -- device files

)  -- end of qualifiers

*  -- executable plain files

+  -- + command name

-  -- follow symlinks toggle

.  -- plain files

/  -- directories

:  -- modifier

=  -- sockets

@  -- symbolic links

A  -- group-readable

D  -- glob dots

E  -- group-executable

F  -- non-empty directories

G  -- owned by EGID

I  -- group-writeable

L  -- + size

M  -- mark directories

N  -- use NULL_GLOB

O  -- + sort order, down

P  -- prepend word

R  -- world-readable

S  -- setgid

T  -- mark types

U  -- owned by EUID

W  -- world-writeable

X  -- world-executable

Y  -- + at most ARG matches

[  -- + range of files

^  -- negate qualifiers

a  -- + access time

c  -- + inode change time

d  -- + device

e  -- execute code

f  -- + access rights

g  -- + owning group

l  -- + link count

m  -- + modification time

n  -- numeric glob sort

o  -- + sort order, up

p  -- named pipes (FIFOs)

r  -- owner-readable

s  -- setuid

t  -- sticky bit set

u  -- + owning user

w  -- owner-writeable

x  -- owner-executable

... all of which can be combined, eg (directories modified today):

```
% du -hs *(/Mm0)

420K    tmp/
```

or, similarly ...

```
% print -rl *(/Mf:u+rx,o-x:)

bin/

dict/

doc/

downloads/

mail/

man/

media/

misc/

perl5/

src/

test/

tmp/
```

best ... khay

----------

