Let’s Write some simple shell scripts

A shell is a command line interpreter. It takes commands and executes them. As such, it implements a programming language.

Let’s look how to write shell script to print hello world
1)write your shell script on some editor like vim.

jinesh@jinesh-Compaq-Presario-CQ40-Notebook-PC:~$ vim first

#content of my first shell script
echo "Hello world"

‘#’ is used to denote comment line.
‘clear’ clear the screen when shell executes.
‘echo’ prints the output on screen.

if we try to run script directly we get the following result.

jinesh@jinesh-Compaq-Presario-CQ40-Notebook-PC:~$ ./first
bash: ./first: Permission denied

2)so our second step is to set permission for the shell script.

jinesh@jinesh-Compaq-Presario-CQ40-Notebook-PC:~$ chmod 755 first

3)run the script using ‘./ script-name’

jinesh@jinesh-Compaq-Presario-CQ40-Notebook-PC:~$ ./first

Hello world

Now lets look on another example. This script print the user information, current date and calender.

jinesh@jinesh-Compaq-Presario-CQ40-Notebook-PC:~$ vim ginfo

#script to print user information who currently login, current date & time

echo "Hello $USER"
echo "Today is  ";date
echo "Number of user login : " ; who |wc -l
echo "Calender"
exit 0

Setting permission and run script.

jinesh@jinesh-Compaq-Presario-CQ40-Notebook-PC:~$ chmod 755 ginfo
jinesh@jinesh-Compaq-Presario-CQ40-Notebook-PC:~$ ./ginfo


Hello jinesh
Today is  
Sun Aug  7 21:21:44 IST 2011
Number of user login : 
    August 2011       
Su Mo Tu We Th Fr Sa  
    1  2  3  4  5  6  
 7  8  9 10 11 12 13  
14 15 16 17 18 19 20  
21 22 23 24 25 26 27  
28 29 30 31

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s