Bash
Bash
- Bash programming
Ola Skavhaug, Joakim Sundnes and Hans Petter Langtangen
August 2011
°
c www.simula.no/˜hpl
Basic Bash programming – p. 2/48
Overview of Unix shells
°
c www.simula.no/˜hpl
Basic Bash programming – p. 3/48
Why learn Bash?
°
c www.simula.no/˜hpl
Basic Bash programming – p. 4/48
Why learn Bash? (2)
°
c www.simula.no/˜hpl
Basic Bash programming – p. 5/48
More information
man bash
“Introduction to and overview of Unix” link in doc.html
°
c www.simula.no/˜hpl
Basic Bash programming – p. 6/48
Scientific Hello World script
Output:
Hello, World! sin(3.4)=-0.255541102027
°
c www.simula.no/˜hpl
Basic Bash programming – p. 7/48
Purpose of this script
Demonstrate
how to read a command-line argument
how to call a math (sine) function
how to work with variables
how to print text and numbers
°
c www.simula.no/˜hpl
Basic Bash programming – p. 8/48
Remark
°
c www.simula.no/˜hpl
Basic Bash programming – p. 9/48
The code, in extended version
File hw.sh:
#!/bin/sh
r=$1 # store first command-line argument in r
s=‘echo "s($r)" | bc -l‘
# print to the screen:
echo "Hello, World! sin($r)=$s"
°
c www.simula.no/˜hpl
Basic Bash programming – p. 10/48
Comments
The first line specifies the interpreter of the script (here /bin/sh,
could also have used /bin/bash)
The command-line variables are available as the script variables
$1 $2 $3 $4 and so on
°
c www.simula.no/˜hpl
Basic Bash programming – p. 11/48
Bash and math
Bourne shell and Bash have very little built-in math, we therefore
need to use bc, Perl or Awk to do the math
s=‘echo "s($r)" | bc -l‘
s=‘perl -e ’$s=sin($ARGV[0]); print $s;’ $r‘
s=‘awk "BEGIN { s=sin($r); print s;}"‘
# or shorter:
s=‘awk "BEGIN {print sin($r)}"‘
Back quotes means executing the command inside the quotes and
assigning the output to the variable on the left-hand-side
some_variable=‘some Unix command‘
# alternative notation:
some_variable=$(some Unix command)
°
c www.simula.no/˜hpl
Basic Bash programming – p. 12/48
The bc program
bc = interactive calculator
Documentation: man bc
bc -l means bc with math library
Note: sin is s, cos is c, exp is e
echo sends a text to be interpreted by bc and bc responds with
output (which we assign to s)
variable=‘echo "math expression" | bc -l‘
°
c www.simula.no/˜hpl
Basic Bash programming – p. 13/48
Printing
°
c www.simula.no/˜hpl
Basic Bash programming – p. 14/48
Convenient debugging tool: -x
°
c www.simula.no/˜hpl
Basic Bash programming – p. 15/48
File reading and writing
Bourne shell and Bash are not much used for file reading and
manipulation; usually one calls up Sed, Awk, Perl or Python to do file
manipulation
File writing is efficiently done by ’here documents’:
cat > myfile <<EOF
multi-line text
can now be inserted here,
and variable interpolation
a la $myvariable is
supported. The final EOF must
start in column 1 of the
script file.
EOF
°
c www.simula.no/˜hpl
Basic Bash programming – p. 16/48
Simulation and visualization script
°
c www.simula.no/˜hpl
Basic Bash programming – p. 17/48
Setting default parameters
#!/bin/sh
pi=3.14159
m=1.0; b=0.7; c=5.0; func="y"; A=5.0;
w=‘echo 2*$pi | bc‘
y0=0.2; tstop=30.0; dt=0.05; case="tmp1"
screenplot=1
°
c www.simula.no/˜hpl
Basic Bash programming – p. 18/48
Parsing command-line options
°
c www.simula.no/˜hpl
Basic Bash programming – p. 19/48
Alternative to case: if
versus
if [ "$option" == "-m" ]; then
m=$1; shift; # load next command-line arg
elif [ "$option" == "-b" ]; then
b=$1; shift;
else
echo "$0: invalid option \"$option\""; exit
fi
°
c www.simula.no/˜hpl
Basic Bash programming – p. 20/48
Creating a subdirectory
dir=$case
# check if $dir is a directory:
if [ -d $dir ]
# yes, it is; remove this directory tree
then
rm -r $dir
fi
mkdir $dir # create new directory $dir
cd $dir # move to $dir
# the ’then’ statement can also appear on the 1st line:
if [ -d $dir ]; then
rm -r $dir
fi
# another form of if-tests:
if test -d $dir; then
rm -r $dir
fi
# and a shortcut:
[ -d $dir ] && rm -r $dir
test -d $dir && rm -r $dir
°
c www.simula.no/˜hpl
Basic Bash programming – p. 21/48
Writing an input file
°
c www.simula.no/˜hpl
Basic Bash programming – p. 22/48
Running the simulation
°
c www.simula.no/˜hpl
Basic Bash programming – p. 23/48
Remark (1)
°
c www.simula.no/˜hpl
Basic Bash programming – p. 24/48
Remark (2)
°
c www.simula.no/˜hpl
Basic Bash programming – p. 25/48
Making plots
Run Gnuplot:
gnuplot -geometry 800x200 -persist $case.gnuplot
if [ "$?" != "0" ]; then
echo "running gnuplot failed"; exit 1
fi
°
c www.simula.no/˜hpl
Basic Bash programming – p. 26/48
Some common tasks in Bash
file writing
for-loops
running an application
pipes
writing functions
file globbing, testing file types
copying and renaming files, creating and moving to directories,
creating directory paths, removing files and directories
directory tree traversal
packing directory trees
°
c www.simula.no/˜hpl
Basic Bash programming – p. 27/48
File writing
outfilename="myprog2.cpp"
# append multi-line text (here document):
cat >> $filename <<EOF
/*
This file, "$outfilename", is a version
of "$infilename" where each line is numbered.
*/
EOF
# other applications of cat:
cat myfile # write myfile to the screen
cat myfile > yourfile # write myfile to yourfile
cat myfile >> yourfile # append myfile to yourfile
cat myfile | wc # send myfile as input to wc
°
c www.simula.no/˜hpl
Basic Bash programming – p. 28/48
For-loops
°
c www.simula.no/˜hpl
Basic Bash programming – p. 29/48
Counters
°
c www.simula.no/˜hpl
Basic Bash programming – p. 30/48
C-style for-loops
declare -i i
for ((i=0; i<$n; i++)); do
echo $c
done
°
c www.simula.no/˜hpl
Basic Bash programming – p. 31/48
Example: bundle files
°
c www.simula.no/˜hpl
Basic Bash programming – p. 32/48
The bundle output file
°
c www.simula.no/˜hpl
Basic Bash programming – p. 33/48
Running an application
°
c www.simula.no/˜hpl
Basic Bash programming – p. 34/48
Pipes
Make a new application: sort all files in a directory tree root, with
the largest files appearing first, and equip the output with paging
functionality:
du -a root | sort -rn | less
°
c www.simula.no/˜hpl
Basic Bash programming – p. 35/48
Numerical expressions
°
c www.simula.no/˜hpl
Basic Bash programming – p. 36/48
Functions
°
c www.simula.no/˜hpl
Basic Bash programming – p. 37/48
Another function example
#!/bin/bash
function statistics {
avg=0; n=0
for i in $@; do
avg=‘echo $avg + $i | bc -l‘
n=‘echo $n + 1 | bc -l‘
done
avg=‘echo $avg/$n | bc -l‘
max=$1; min=$1; shift;
for i in $@; do
if [ ‘echo "$i < $min" | bc -l‘ != 0 ]; then
min=$i; fi
if [ ‘echo "$i > $max" | bc -l‘ != 0 ]; then
max=$i; fi
done
printf "%.3f %g %g\n" $avg $min $max
}
°
c www.simula.no/˜hpl
Basic Bash programming – p. 38/48
Calling the function
°
c www.simula.no/˜hpl
Basic Bash programming – p. 39/48
File globbing
°
c www.simula.no/˜hpl
Basic Bash programming – p. 40/48
Testing file types
if [ -f $myfile ]; then
echo "$myfile is a plain file"
fi
# or equivalently:
if test -f $myfile; then
echo "$myfile is a plain file"
fi
if [ ! -d $myfile ]; then
echo "$myfile is NOT a directory"
fi
if [ -x $myfile ]; then
echo "$myfile is executable"
fi
[ -z $myfile ] && echo "empty file $myfile"
°
c www.simula.no/˜hpl
Basic Bash programming – p. 41/48
Rename, copy and remove files
°
c www.simula.no/˜hpl
Basic Bash programming – p. 42/48
Directory management
# make directory:
$dir = "mynewdir";
mkdir $mynewdir
mkdir -m 0755 $dir # readable for all
mkdir -m 0700 $dir # readable for owner only
mkdir -m 0777 $dir # all rights for all
# move to $dir
cd $dir
# move to $HOME
cd
# create intermediate directories (the whole path):
mkdirhier $HOME/bash/prosjects/test1
# or with GNU mkdir:
mkdir -p $HOME/bash/prosjects/test1
°
c www.simula.no/˜hpl
Basic Bash programming – p. 43/48
The find command
°
c www.simula.no/˜hpl
Basic Bash programming – p. 44/48
Applications of find (1)
Find all files larger than 2000 blocks a 512 bytes (=1Mb):
find $HOME -name ’*’ -type f -size +2000 -exec ls -s {} \;
°
c www.simula.no/˜hpl
Basic Bash programming – p. 45/48
Applications of find (2)
Find all files not being accessed for the last 90 days:
find $HOME -name ’*’ -atime +90 -print
and move these to /tmp/trash:
find $HOME -name ’*’ -atime +90 -print \
-exec mv -f {} /tmp/trash \;
°
c www.simula.no/˜hpl
Basic Bash programming – p. 46/48
Tar and gzip
The tar command can pack single files or all files in a directory tree
into one file, which can be unpacked later
tar -cvf myfiles.tar mytree file1 file2
# options:
# c: pack, v: list name of files, f: pack into file
# unpack the mytree tree and the files file1 and file2:
tar -xvf myfiles.tar
# options:
# x: extract (unpack)
°
c www.simula.no/˜hpl
Basic Bash programming – p. 47/48
Two find/tar/gzip examples
°
c www.simula.no/˜hpl
Basic Bash programming – p. 48/48