Shell Scripting Examples – Learn Shell Scripting the fastest way!
Shell Scripting can be used for creating various scripts which help in complex mathematical calculations or for UNIX operations.
A few examples are given below:
1. To Compute square of n:
1. First open a file.
server501:# vi square.sh
Then ESC i, to go to insert mode
Paste the code.
n=1
while [ ${n} -lt 10 ]; do
echo .`expr ${n} \* ${n}`.
n=`expr ${n} + 1`
done
Then ESC :wq , to save and exit
Now to see the file do cat square.sh
server501:# cat square.sh
n=1
while [ ${n} -lt 10 ]; do
echo .`expr ${n} \* ${n}`.
n=`expr ${n} + 1`
done
Give execute privilege to square.sh
r w x r w x r w x
user group others
111 000 000
7 0 0
Read, write and execute privs for the user
server501:# chmod 700 square.sh
server501:# ./square.sh
.1.
.4.
.9.
.16.
.25.
.36.
.49.
.64.
.81.
2. To get some information of the user currently logged in.
server501:# chmod 700 userinfo.sh
server501:# cat userinfo.sh
#!/bin/sh
echo “Hello $USER”
echo “Today is \c “;date
echo “Number of user login : \c” ; who | wc -l #who command gives all users logged in. wc gives word count.
echo “Calendar”
exit 0
server501:# ./userinfo.sh
Hello angelina
Today is Fri Dec 30 02:02:37 MST 2011
Number of user login : 18
Calendar
==================================================================================
echo “Number of user login : \c” ; who | wc -l #who command gives all users logged in. wc gives word count.
This is how you give comments
3. To check if a file exists or not. If exits check whether it is readable.
server501:# cat fileread.sh
echo “Enter the name of your file:”
read filename
if [ ! -f $filename ]
then
echo “file does not exist”
elif [ ! -r $fname ]
then
echo “File is not readable”
else
echo “File is readable”
fi
server501:# chmod 700 fileread.sh
server501:# ./fileread.sh
Enter the name of your file:
page.txt
File is readable
4. To add items to an inventory
server501:# cat inventory.sh
choice=y
while [ “$choice” = “y” ]
do
echo “Enter code and desc:”
read code
read desc
echo “$code|$desc” >> inventory
echo “More Items (Enter yes/no only)? ”
read choice
case $choice in
Y*|y*) choice=y ;;
N*|n*) choice=n ;;
*) echo “Invalid answer”;
esac
done
server501:# ./inventory.sh
Enter code and desc:
101
Brush
More Items (Enter yes/no only)?
n
============================================
Running the code for the second time
server501:# ./inventory.sh
Enter code and desc:
102
Paste
More Items (Enter yes/no only)?
yes
Enter code and desc:
103
Milk
More Items (Enter yes/no only)?
n
======================================
server501:# cat inventory
101|Brush
102|Paste
103|Milk