Shell Scripting What is Shell Programming? Putting UNIX commands in a file Seldom used where speed is important Often used to manipulate files To create a simple shell script file: $ vi test.sh or $ cat > test.sh To execute a shell script file: $ sh filename Or $./filename
Basic Operators Arithematic Operators : [+, -, \*, /, %, =,!=,==.] Relational Operators : [-eq,-ne,-gt,-lt,-ge,-le] Boolean Operators : [-o,-a,!] String Operators : [ -z, -n, =, !=, str ] File Test operators : [ -b,-c,-d,-e,-f,-r,-w,-x, -s]
Shell Decision Statement If..else statements if [ condition(s) ] then command(s) fi case...esac Statement case word in pattern1) Statement(s) to be executed if pattern1 matches ;; esac
Iterative/Looping Statements While Loop while [ condition ] do Command (s) done Until Loop until [ condition ] do command (s) done For Loop for var in word1 word2... wordN do Command(s) done
String Handling and Command line arguments String handling with test command test str test –n str test –z str String handling with expr command Length of the string : n=`expr "$str" : ‘.*’` ; Extracting a sub-string: ` expr “$str” : ‘……\(..\)’` Command line arguments The command-line arguments $1, $2, $3...$9 are also called positional parameters $0 points to actual command/shell script/program Eg: echo “Program name is $0” echo “First argument is $1” echo “Second argument is $2” While executing $ sh test.sh arg1 arg2 Output: Program name is test First argument is arg1 Second argument is arg2