You are on page 1of 9

BABU BANARASI DAS UNIVERSITY

UNIX AND SHELL PROGRAMMING


ASSIGNMENT-4
(Loops and conditional statements in UNIX)

SUBMITTED BY - SUBMITTED TO-


Srishti gupta Mam Nilu

MCA -2

IV semester

2190212054
1. IF….ELSE statement-
Program to compare if the two numbers are equal-
2. a=10
3. b=20
4.
5. if [ $a == $b ]
6. then
7. echo "a is equal to b"
8. else
9. echo "a is not equal to b"
10. Fi

2. for loop-
Example 1-Program of “for loop” to print “Welcome n times”-
#!/bin/bash
for i in 1 2 3 4 5
do
echo "Welcome $i times"
done
Output-

Example 2- Program to print numbers from 0 to 9


Live Demo
#!/bin/sh

for var in 0 1 2 3 4 5 6 7 8 9
do
echo $var
done

Output-

3. until loop-
Example 1- Program to display that the until loop prints the current
value of the variable and counter increments the variable by one.
#!/bin/bash

counter=0

until [ $counter -gt 5 ]


do
echo Counter: $counter
((counter++))
done

Output-

Example 2- This program will print the value of ‘a’ two times from 1 to
a=1

until [ $a -ge 3 ]

do

echo “value of a=” $a

a=`expr $a + 1`

done
Output-

4. while loop-

Example 1- This program will print the value of ‘a’ five times, from 1 to
5.

a=1

while [ $a -le 5 ]

do

echo “value of a=” $a

a=`expr $a + 1`

done
Output-

Example 2-Program of while loop to calculate factorial of a number

#!/bin/bash

counter=$1

factorial=1

while [ $counter -gt 0 ]

do

factorial=$(( $factorial * $counter ))

counter=$(( $counter - 1 ))

done

echo $factorial
Output-

5. read command-

Example1 - Echo "one two three four" and pipe it to the while loop,


where read reads the first word into word1, the second into word2,
and everything else into word3.

echo "one two three four" | while read word1 word2 word3; do

echo "word1: $word1"

echo "word2: $word2"

echo "word3: $word3"

done
Output-

Example 2- Program to read first middle and last name in unix and
print it.
#!/bin/bash

read first middle last

echo "Hello $first $middle $last"

Output-

6. Array-

Example 1- Program of array


array1[0]=one

array1[1]=1

echo ${array1[0]}

echo ${array1[1]}

array2=( one two three )


echo ${array2[0]}

echo ${array2[2]}

array3=( [9]=nine [11]=11 )

echo ${array3[9]}

echo ${array3[11]}

read -a array4

for i in "${array4[@]}"

do

echo $i

done

exit 0

Output-

You might also like