Let us look into how to write shell scripts to:
- Find the sum of the n natural number
- Swap the two values using only two variables
- To find the sum of n even numbers
- To print the multiplication table of a given number
Shell scripting is programming through which we write several lines of command together to execute. We can either have extension .sh, .bash, etc. depending on the type of shell we use.
Here, let us look into shell scripts with extension .sh which is used with the Bourne Shell.
1. Find the sum of the n natural number
Sample Code:
#to find sum of n numbers
#! /bin/sh
echo "Enter n"
read n
i=1
sum=0
while [ $i -le $n ]
do
read p
sum=$(expr $sum + $p)
i=$(expr $i + 1)
done
echo $sum
Sample Output:
2. Swap the two values using only two variables
Sample Code:
#!bin/sh
echo 'Enter value of x'
read x
echo 'Enter value of y'
read y
y=$((y+x))
x=$((y-x))
y=$((y-x))
echo "The value of x and y after swap is x=$x and y=$y"
Sample Output:
3. To find the sum of n even numbers
Sample Code:
#! /bin/sh
#sum of even numbersE
read n
sum=0
for ((i=1;i<=n;i++))
do
if ((i%2==0))
then
sum=$((sum+i))
fi
done
echo $sum
Sample Output:
4. To print the multiplication table of a given number
Sample Code:
#!bin/sh
i=1;
echo 'Enter the multiplier number'
read n
echo 'Enter the limit of the multiplication number'
read limit
echo "The multiplication table of $n":
for ((i=1;i<=limit;i++))
do
pro=$((n*i))
echo "$n * $i = $pro"
done
Sample Output:
You may also like to read: