shell scripting

Posted under » Linux on 21 October 2009

A shell script is similar to the windows batch file running PowerShell. It will execute commands listed on the text file. Shell scripting is an important part of process automation in Linux. Scripting helps you write a sequence of commands in a file and then execute them. It is powerful when you combine it with cron.

It is also called a bash script. Bash scripts end with a .sh Scripts are also identified with a shebang. Shebang is a combination of bash # and bang ! followed the the bash shell path to the bash interpreter. This is the first line of the script.

To find the path of bash:

$ which bash
$ /usr/bin/bash

Example test.sh

#! /usr/bin/bash
# Script to print user information who currently login , current date & time
#
clear
echo "Hello $USER"
echo "Today is \ ";date
echo "Number of user login : \ " ; who | wc -l
echo "Calendar"
cal
exit 0

In order to run, chmod the file to make it executable. Execute it by typing the file name out with its location (relative or full) or type sh in front.

$ chmod 755 test.sh // or chmod u+x test.sh
$ ./test.sh
$ /var/script/test.sh
$ sh test.sh

Example: Let's find the triangle type by reading the lengths of its sides. The read function will ask user to input the variable.

...
read a
read b
read c

if [ $a == $b -a $b == $c -a $a == $c ]
then
echo EQUILATERAL

elif [ $a == $b -o $b == $c -o $a == $c ]
then 
echo ISOSCELES
else
echo SCALENE

fi

This however, does not work for me. I think it is best that we do this sort of thing using Python.

Sometimes it is easier to create Bash Alias.

An advanced example.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data