Shell script tutorial
Liang Liu
2021-04-16
A shell script is a series of bash commands that can be executed by shell. A nice tutorial for shell scripting is available at the shell tutorial and Bash scripting cheatsheet.
The first shell script “Hello World” using echo.
#!/bin/sh
echo "Hello World"
Read input from screen
#!/bin/sh
echo "What is your name?"
read NAME
echo "Hello, $NAME"
Read parameters from command lines: ./script.sh 3 alpha
#!/bin/sh
echo $1 $2
echo $@
Array variables. All shell variables should be capitalized
#!/bin/sh
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "names: ${NAME[*]}"
for I in ${NAME[*]}
do
echo $I
done
Math expression using `expr`
#!/bin/sh
val=`expr 2 + 2`
echo "Total value : $val"
Flow: make a decision if, elif, else
#!/bin/sh
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "names: ${NAME[*]}"
for I in ${NAME[*]}
do
echo $I
if [ $I == "Ayan" ]
then
break
fi
done
Loop: for, until, while
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
if [ $a -eq 5 ]
then
break
fi
a=`expr $a + 1`
done
Define a function
#!/bin/sh
Hello () {
echo "Hello World $1 $2"
}
Hello Zara Ali