Skip to content

Shell Scripting

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.

See if control block

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.

Terminal window
while [[ ! -a lockfile ]];
do
echo waiting for 2 seconds
sleep 2
done

For each line in a file

Terminal window
while read line; do echo line; done < inputfile.txt
Terminal window
for arg in one two three
do
echo $arg
done

List all arguments to the current script

Terminal window
for arg in $@
do
echo $arg
done

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

-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.

-a repair.lock tests for the existence of repair.lock

-o represents logical or. Use it to combine two conditionals together

Terminal window
if [ $IORUNNING != "Yes" -o $SQLRUNNING != "Yes" ]

This is useful for checking return codes

Terminal window
if [ $result -ne 0 ]
then
echo failed with code: $result
fi

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

Terminal window
dir=/a/b/c
basedir=`basename $dir`
echo $basedir
# this will output 'c'

An alternative to backticks is $()

Terminal window
dir=/a/b/c
basedir=$(basename $dir)
echo $basedir
# this will output 'c'

perm will test file permissions.

To find all files that everyone (all) can read

Terminal window
find -type f -perm -a+r

To find all files that not everyone can read

Terminal window
find -type f ! -perm -a+r

To find all files that have permission 644 or more permissive

Terminal window
find -type f -perm -644