Friday, 19 September 2014

Shell Script

Shell script defined as:
"Shell Script is series of command written in plain text file. Shell script is just like batch file is MS-DOS but have more power than the MS-DOS batch file."
Why to Write Shell Script ?
  • Shell script can take input from user, file and output them on screen.
  • Useful to create our own commands.
  • Save lots of time.
  • To automate some task of day today life.
  • System Administration part can be also automated.

How to write shell script

Following steps are required to write shell script:
(1) Use any editor like vi or mcedit to write shell script.
(2) After writing shell script set execute permission for your script as follows
syntax: 
chmod permission your-script-name

Examples:
$ chmod +x your-script-name
$ chmod 755 your-script-name

Note: This will set read write execute(7) permission for owner, for group and other permission is read and execute only(5).
(3) Execute your script as
syntax: 
bash your-script-name
sh your-script-name
./your-script-name

Examples:
$ bash bar
$ sh bar
$ ./bar

if...else...fi

If given condition is true then command1 is executed otherwise command2 is executed.
Syntax:

           if condition
           then
                       condition is zero (true - 0)
                       execute all commands up to else statement
 
           else
                       if condition is not true then
                       execute all commands up to fi
           fi

for Loop

Syntax:
            for { variable name } in { list }
            do
                     execute one for each item in the list until the list is
                     not finished (And repeat all statement between do and done)
            done

while loop

Syntax:
           while [ condition ]
           do
                 command1
                 command2
                 command3
                 ..
                 ....
            done




No comments:

Post a Comment