Bash Samples
From OriWiki
Script1
#!/bin/sh
#this is a comment
#invoke a program
#../../exercises/ex2/q3 &
# usage of `expression`
grep `whoami` /etc/passwd
# arguments given to the script
echo the number of arguments given to this script: $#
echo the name of this script: $0
echo the first four arguments are: $1 $2 $3 $4
echo
# arithmetic expressions
echo the expression 2 + 3 equals: `expr 2 + 3`
echo the expression 2 \* 3 equals: `expr 2 \* 3`
#variables
a=17 #note that a = 17 (with spaces) will not set a value to a
b=`expr $a + 7`
echo -e a=$a "\n"b=$a+7 "\n"b=$b
#if statement
if [ $# -ne 0 ]
then
if [ $1 = hey ]
then
echo the first argument is hey
else
echo the first argument is not hey
fi
fi
# while loop
a1=1
a2=1
while [ $a2 -lt 50 ] #the spaces are important
do
echo -n $a1 " "
a3=`expr $a1 + $a2`
a1=$a2
a2=$a3
done
echo
#until loop
until [ 10 -gt $a1 ]
do
echo -n $a1 ""
a1=`expr $a1 - 1`
done
echo
#for loop
names="yosi pesi moshe tzili gile"
c=1
for n in $names
do
echo name $c: $n
c=`expr $c + 1`
done
Submit
#! /bin/sh
if [ $# -ne 1 ]
then
echo -e "usage:\n" $0 "<ex num>"
exit 1
fi
if !(test -r readme) # FILE exists and is readable
then
echo "no readme file !"
exit 1
fi
if !(test -r makefile)
then
echo "no makefile file !"
exit 1
fi
tmpName=tmp
count=1
while true
do
tmpDir=$tmpName$count
if !(test -r $tmpDir)
then
break
fi
count=`expr $count + 1`
done
tarName=ex$1.tgz
echo "----------making tar.."
tar czvf $tarName *.cpp *.h makefile readme
echo "----------creating directory" $tmpDir ".."
mkdir $tmpDir
echo "----------copying tgz to" $tmpDir ".."
cp $tarName $tmpDir
cd $tmpDir
echo "----------extracting tgz.."
tar xzvf $tarName
echo "----------make.."
make
echo "----------run.."
make run
cd ..
rm -fr $tmpDir
echo -e "\n\n ------All seems to be ok."
exit 0

