Bash Script Cheat Sheet
Bash Script Cheat Sheet
shtml
File Manipulation
> file >> file >file 2>&1 < file a|b create (overwrite) file append to file both output and errors to file read from file pipe output from 'a' as input to 'b'
Test Operators
if [ $x -lt $y ]; then # do something fi Numeric Tests lt gt read text file line by line eq ne ge le less than greater than equal to not equal greater or equal less or equal
Variable Substitution
${V:-def} ${V:=def} ${V:?err} $V, or def if unset $V (set to def if unset) $V, or err if unset
Conditional Execution
c1 || c2 c1 && c2 run c1; if it fails, run c2 run c1; if it works, run c2
Common Constructs
while read f do echo Line is $f done < file $ grep foo myfile afoo foo foobar $ cut -d: -f5 /etc/passwd Dilbert foo=`ls`
find matching lines get field with delimiter get output of command
case $foo in a) echo foo is A ;; b) echo foo is B ;; *) echo foo is not A or B ;; esac doubleit() { expr $1 \* 2 } doubleit 3 # returns 6 function declaration and calling syntax A for loop for i in * do echo File is $i done iterates through its input (which is subject to globbing) case is a good way to avoid iterating through many if/elif/elif/elif constructs.
Networking
ifconfig -a netstat -r ssh u@host scp file.txt \ u@host: list all network interfaces show routers log in to host as user u copy file.txt to host as user u
Argument Variables
$0 $1 $2 ... $9 $* $# program name 1st argument 2nd argument ... 9th argument all arguments No. of arguments
General Admin
less file alias l='ls -l' tar cf t.tar \ list_of_files cal 3 1973 df -h truss -p PID display file, page by page create l as alias for ls -l create a tar archive t.tar from the listed dirs/files display a calendar (Mar 73) show disk mounts show syscalls of PID
Useful Variables
$IFS $? $SHELL LANG Internal File Separator return code from last program what shell is running this script? Language; C is US English awk '{ print $5 }' file sed s/foo/bar/g file