FOSS / LAMP
Session 4
Shell Scripting
Scripting Basics • Shell scripts are text files that contain a series of commands or statements to be executed. • It is useful for – To automate – Creating applications – Perform system administration
Creating shell scripts • Text editor vi is used to create a text file containing commands • Executing script $ bash filename
• Make the script executable $ chmod a+x filename
Examples $ vi file1 echo "enter the source file" read f1 echo "enter the destination file" read f2 cp $f1 $f2 echo "file is copied"
$ vi file2 read -p "enter source file" f1 read -p "enter destination file" f2 mv $f1 /opt/$f2 echo "file is moved"
If statements $ vi file3 read a read b if [ $a -gt $b ] ; then echo "a is greater $a"; else echo "b is greater $b"; fi
Nested If • $ vi file4 read a b c if [ $a -gt $b ] && [ $a -gt $c ]; then echo “ a is greater $a”; elif [ $b -gt $a ] && [ $b -gt $c ]; then echo “b is greater $b”; else echo “c is greater $c”; fi
For loop $ vi file5 for i in {0..5}
for i in $(seq 1 2 10)
do
do
echo "$i";
echo "$i";
done
done
• $ vi file6 read n for ((i=1; i<=$n; i++)) do echo "$i"; done
While loop $ vi file6
while [ $i -le $n ]
echo "how many users you want to add"
do
read n
useradd $name$i
echo "enter the stating name of the user"
i=`expr $i + 1`
read name i=1
echo " creatibng user $name$i"
done
Case Statement • $ vi file8 read choice echo "enter the num1 num2" read n1 n2 case $choice in 1)echo "ADD : ` expr $n1 + $n2 `";; 2)echo “MUL : ` expr $n1 \* $n2 `”;; esac
Thanks a lot for your attention !!