Shell Scripting

Shell scripting snippets

Published: Monday, 27 July 2015

Bash Examples

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

if statement

See if control block

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 2
done

for each line

For each line in a file

while read line; do echo line; done < inputfile.txt

for loop

for arg in one two three
do
  echo $arg
done

List all arguments to the current script

for arg in $@
do
  echo $arg
done

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

-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

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

Logic operators

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

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

Integer comparison

This is useful for checking return codes

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

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/c
basedir=`basename $dir`
echo $basedir
# this will output 'c'

An alternative to backticks is $()

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

Find examples

permissions

perm will test file permissions.

To find all files that everyone (all) can read

find -type f -perm -a+r

To find all files that not everyone can read

find -type f ! -perm -a+r

To find all files that have permission 644 or more permissive

find -type f -perm -644
Shell Scripting