Cheat Sheet
Cheat Sheet
Cheat Sheet
Sept 2012 Shell Scripting Cheat Sheet for Unix and Linux Online: http://steve-parker.org/sh/sh.shtml Book: http://steve-parker.org/shellscripting Test Operators
if [ $x -lt $y ]; then # do something fi Numeric Tests
File Redirection
> file >> file < file a|b create (overwrite) file append to file read from file Pipe 'a' as input to 'b'
Variable Substitution
${V:-default} ${V:=default} ${V:?err} $V, or default if unset $V (set to default if unset) $V, or err if unset
Conditional Execution
cmd1 || cmd2 cmd1 && cmd2 run cmd1; if fails, run cmd2 run cmd1; if ok, run cmd2
Common Constructs
$ while read f > do > echo Line is $f > done < file $ grep foo myfile afoo foo foobar $ cut -d: -f5 /etc/passwd Steve Parker $ cmd1 || cmd2 $ cmd1 && cmd2 case $foo in a) echo foo is A ;; b) echo foo is B ;; *) echo foo is not A or B ;; esac myvar=`ls` doubleit() { expr $1 \* 2 } doubleit 3 # returns 6 get output of ls into variable function declaration and syntax for calling it note that ;; is required at the end of each section note: $ prompt becomes > find lines in myfile containing the text foo get 5th field delimited by colon run cmd1; if fails, run cmd2 run cmd1; if it works, run cmd2 act upon the value of a variable read text file line by line
lt gt eq ne ge le
less than greater than equal to not equal greater or equal less or equal
Files
mv /src /dest ls a* ls *a ls -ltr ls -lSr ls -a find /src -print \ | cpio -pudvm move /src into /dest list files beginning with a list files ending with a list oldest first, newest last list smallest first, biggest last list all files, including hidden copy /src into current directory, preserving links, special devices, etc.
Preset Variables
String Tests = z n equal to zero length not zero length $SHELL $RANDOM $$ $? $! Logical Tests && || ! logical AND logical OR logical NOT what shell am I running? provides random numbers PID of current process return code from last cmd PID of last background cmd
Arguments
$0 $1 $2 $# $* program name 1st argument 2nd argument no. of arguments all arguments