Shell Scripting

Bash Examples

Add "set -e" as the first line of your script so it will exit whenever a command returns as error. This means you won't need to keep checking for return codes.

Control

if


if [ -z $IORUNNING ]
then
  echo check that io is running
fi
        

while


while [[ -a $lockfile ]];
do
  sleep 10
done

The above keeps checking for the existing of a file every 10 seconds. When it exists it will continue out of the loop.

For each line in a file


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

Bash logic tests

Bash provides some 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 $VARIABLE returns true if null

$A != $B not equals

-n "$VARIABLE" returns true if length is non-zero

File tests

if [ -a repair.lock ]

Tests for the existence of the repair.lock file. Handy for lock files.

Logical Operators

-o logical or


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

Use the "!" operator.

if [ ! -a repair.lock ]

The above is true if the repair.lock file does not exist.

Integer Comparison

This is useful for checking return codes.

not equals is -ne

result=$?
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'
      

foreach argument

#!/bin/bash

for arg in $@
do
  echo $arg
done;

find

test: perm

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

Published: Monday, 27 July 2015