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
The shell scripting is a 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
#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
2. Swap the two values using only two variables
#!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"
3. To find the sum of n even numbers
#! /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
4. To print the multiplication table of a given number
#!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
You may also like to read: