Bash Scripting

Cheatsheet
$0          command name $1          first argument $*          all arguments

Lists
Lists come in different variants - sequential execution: $ printf huba; printf hop hubahop AND list - the second command is executed if and only if the first command returns an exit status of zero.

This example shows that if the first command fails, the second one is not executed: $ cat /bin/huba && echo "/bin/huba exists" cat: /bin/huba: No such file or directory We can also use conditional expressions enclosed in ' '. This one tests whether /bin/cp exists: $ [ -e /bin/cp ] && echo "cp exists" cp exists

OR lists operate conversely of AND lists, the second command is executed if and only if the first returns a non-zero exit status.

An example: $ cat /bin/huba || echo "/bin/huba does NOT exist" /bin/huba does NOT exist

Arithmetic
Set x=0, add 1 to x and print: $ x=0; x=$((x+1)); echo "x is $x" x is 1

show calendear for jan-feb 2005: $ for month in 1 2; do cal -m $month 2005; done January 2005 Mo Tu We Th Fr Sa Su                1  2 3 4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31     February 2005 Mo Tu We Th Fr Sa Su    1  2  3  4  5  6 ...

ls-replacement with built-in danish insult: $ echo Idiot, du har fÃ¸lgende filer:;for f in *;do echo $f \(svin\);done

print square numbers between 1 and 36: $ x=1; while [ $x -le 10 ]; do echo "x = $((x*x))"; x=$((x+1)); done or the clever one: $ x=0; while [ $x -lt 10 ]; do echo "x = $((++x**2))"; done a cool table of 2^n as dec/hex: $ x=-1; while [ $((x++)) -lt 30 ]; do printf "%10d -- %10x (hex)\n" $((1<<x)) $((1<<x)); done 1 --         1 (hex) 2 --         2 (hex) 4 --         4 (hex) 8 --         8 (hex) 16 --        10 (hex) 32 --        20 (hex) 64 --        40 (hex) ...

Examples
very strange: look up all words in /usr/share/dict beginning with 'pig', and print them, converting 'pig' to 'svin', removing apostrophed endings and repolacing linefeeds with '-'. Finally, we make all the words uppercase: $ for word in `look pig`; do echo $word|sed -e "s/[Pp]ig/svin/g" -e "s/'.*//g"|tr '\n' '-' \ |tr a-z A-Z;done;echo

list all the descriptions of the commands in /usr/bin $ whatis `ls /usr/bin`|sed -e "/nothing appropriate/d" -e "/No manpage for/d"|less

rename all files in directory starting with an underscore to same name without underscore $ for f in _*; do mv $f `ls $f | sed -e "s/_//"`;done