Shell Scripting
Bash Examples
Section titled “Bash Examples”exit immediately on error
Section titled “exit immediately on error”Add set -e as the first line of your script, so it will exit as soon as a command returns a non-zero status (error).
This means you won’t need to keep checking for return codes.
Control
Section titled “Control”if statement
Section titled “if statement”See if control block
while loop
Section titled “while loop”The below busy wait tests for the existence of a file named lockfile every 2 seconds. When it exists, the script will
continue out of the loop.
while [[ ! -a lockfile ]];do echo waiting for 2 seconds sleep 2donefor each line
Section titled “for each line”For each line in a file
while read line; do echo line; done < inputfile.txtfor loop
Section titled “for loop”for arg in one two threedo echo $argdoneList all arguments to the current script
for arg in $@do echo $argdonebash logic tests
Section titled “bash logic tests”Bash provides conditional expressions that can be used as tests as part of if statements.
You can find documentation from the command line under info bash -> Bash Features -> Bash Conditional Expressions
String Comparison
Section titled “String Comparison”-z $FOO returns true if the length of FOO is zero.
$A != $B returns true if strings are not equal.
-n $FOO returns true if length is non-zero.
File tests
Section titled “File tests” -a repair.lock tests for the existence of repair.lock
Logic operators
Section titled “Logic operators”-o represents logical or. Use it to combine two conditionals together
if [ $IORUNNING != "Yes" -o $SQLRUNNING != "Yes" ]Integer comparison
Section titled “Integer comparison”This is useful for checking return codes
if [ $result -ne 0 ]then echo failed with code: $resultfibackticks
Section titled “backticks”You can use the text output of one program for the input of another. You can also assign the text output to a different variable
dir=/a/b/cbasedir=`basename $dir`echo $basedir# this will output 'c'An alternative to backticks is $()
dir=/a/b/cbasedir=$(basename $dir)echo $basedir# this will output 'c'Find examples
Section titled “Find examples”permissions
Section titled “permissions”perm will test file permissions.
To find all files that everyone (all) can read
find -type f -perm -a+rTo find all files that not everyone can read
find -type f ! -perm -a+rTo find all files that have permission 644 or more permissive
find -type f -perm -644