Basics of UNIX SHELL Scripting : Part-2

Continued from http://www.databaseetl.com/learn-unix-shell-scripting-with-below-simple-steps-part1/

  1. Loops in Shell Script

A loop structure is a programming mechanism for repeating a series of commands. FOR loop is most frequently or often used by the programmers. Except FOR, there are two more loops available i.e. WHILE loop and UNTIL loop.

Let’s discuss basics of them one by one.

  • FOR loop

The syntax of FOR loop is

For var in va1 var2 var3 . . .

do
command(s)
done

Here FOR, IN, DO and DONE are the keywords.

Now loop will keep repeating for each variable i.e. var1, var2, var3 etc. For each variable it will execute a command. DO will start the for loop once ‘var’ gets assigned from the declared variables i.e. will start executing commands and done will tell for loop that current loop completed and go for the next variable.

  • WHILE Loop

The Sytax for WHILE Loop is

While command1

Do

Command2 or statements

Done

Here WHILE, DO and DONE are the Keywords.

Now, it will enter into the loop when command1 results ‘true’.

For example, I want to print numbers from 1 to 10

a=0while [ $a -lt 10 ]do   echo $a   a=`expr $a + 1`done

Output will be

0

1

2

3

4

5

6

7

8

9

  • UNTIL loop

The syntax for UNTIL loop is

Until command1

Do

Command2 or statements

Done

Here UNTIL, DO, and DONE are the keywords,

It works similar to WHILE loop. If command1 evaluates ‘true’ then commands2 or statements will be executed.


  1. Shell Script Return Code

Return codes, as name suggests these are the numbers returned by the commands or expressions within the shell script.

It’s similar to EXIT code in UNIX, exit 0 is successfully completed and other than zero, it unsuccessful.

Let’s discuss it by example,

#This shell script example demonstrates use of the return code
scriptname=$1
if [ -f $scriptname ]
then
echo “return code of expression was $?”
echo “$scriptname exists”
else
echo “return code of expression was $?”
echo “$scriptname does not exist”
fi
exit 0

Script will return 0 if ‘scriptname’ exists otherwise it will be 1 if it doesn’t exist.

 


(Edit)

Leave a Reply

Logged as admin. Log out »

© 2017 Database ETL. All rights reserved.
Skip to toolbar Log Out