Aug 28, 2016

Bash Shell Script Sample Code - Part 1

1. Read user input and display message Welcome

#!/bin/bash
echo 'read_input=?' ; 
read read_input
echo "Welcome on $read_input" 
Sample output:
read_input=?
Devinline
Welcome on Devinline

 2. Print Even natural numbers up to given N.
#!/bin/bash
echo 'Enter input value N=?' ; 
read N
x=0 #no space in variable declaration
zero=0
t=9
while [ $x -le $N ]
do
 let p=$x%2; 
 if [ $p -eq 0 ]
 then
  echo "$x"
 fi
 x=$((x+1))
done
Sample Output:-
[cloudera@quickstart Desktop]$ sh even.sh
Enter input value N=?
15
0
2
4
6
8
10
12
14

3. Print 1 to N  (N is read as user input)
#!/bin/bash
x=1
echo 'Enter input value N=?' ; 
read N
while [ $x -le $N ]
do 
    echo $x
    x=$((x+1)) #Arithmatic compound expression
done
Sample output:-
Enter input value N=?
8
1
2
3
4
5
6
7
8

4. Arithmetic operation - read two number from user and perform addition, subtraction, multiplication and division

#!/bin/bash
echo 'Enter input value1 x=?' ;
read x
echo 'Enter input value2 y=?' ;
read y
echo "Sum is $((x+y))"
echo "Subtraction is $((x-y))"
echo "Multiplication is $((x*y))"
echo "Division is $((x/y))"
Sample Output:-
Enter input value1 x=?
12
Enter input value2 y=?
4
Sum is 16
Subtraction is 8
Multiplication is 48
Division is 3

5. Compare two number entered as user input (If-else block)

#!/bin/bash
echo 'Enter input value1 x=?' ;
read x
echo 'Enter input value2 y=?' ;
read y
if [ $x -gt $y ]
then
 echo "X is greater than Y" 
elif [ $x -lt $y ] 
then 
    echo "X is less than Y"  
else 
    echo "X is equal to Y"
fi 
Sample output:-
Enter input value1 x=?
12
Enter input value2 y=?
34
X is less than Y

6. Using Switch case - Print YES if Y/y is user input and NO for N/n 6666666666666666

#!/bin/bash
echo 'Enter input char=?' ;

read char
case "$char" in
 Y) echo "YES" 
  ;;
 y) echo "YES" 
  ;;
        n) echo "NO" 
  ;;
 N)   echo "NO" ;;
esac
Sample output:-
Enter input char=?
y
YES

7. Check triangle is SCALENE,ISOSCELES or EQUILATERAL . Get sides of triangle as user input. 

#!/bin/bash
echo 'Enter triangle side1 length x=?' ;
read x
echo 'Enter triangle side1 length y=?' ;
read y
echo 'Enter triangle side1 length z=?' ;
read z
if [ $x -eq $y ] && [ $y -eq $z ]
then
    echo "EQUILATERAL triangle"
elif [ $x -eq $y ] ||  [ $y -eq $z  ] || [ $x -eq $z ]
then     
    echo "ISOSCELES triangle"
else
    echo "SCALENE triangle"
fi 
Sample output:-
Enter triangle side1 length x=?
6
Enter triangle side1 length y=?
5
Enter triangle side1 length z=?
5
ISOSCELES triangle

8. Sum of N natural numbers. Take user input value of N.


#!/bin/bash

echo -n "Enter number N=?"
read N

s=0 # here sum

for((i=1; i <=N ; i++))
do
 let s=$s+$i 
done

echo "sum= "$s
Sample output:-
[cloudera@quickstart Desktop]$ sh sum.sh
Enter number N=?5
sum= 15

Location: Hyderabad, Telangana, India