Let us look into how to write shell scripts to:

  1. Find the sum of the n natural number
  2. Swap the two values using only two variables
  3. To find the sum of n even numbers
  4. 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
Code language: PHP (php)

Sample Output:

Shell script to print sum of n numbers
Shell script to print the sum of n numbers

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"
Code language: JavaScript (javascript)

Sample Output:

Shell script to swap values of two variables using only two variables
Shell script to swap values of two variables using only two variables

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
Code language: PHP (php)

Sample Output:

Shell Script to find the sum of n even numbers
Shell Script to find the sum of n even numbers

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
Code language: PHP (php)

Sample Output:

Shell Script To print the multiplication table of a given number
Shell Script To print the multiplication table of a given number

You may also like to read:

  1. Phone-book Using Shell Script
  2. Some Shell Scripts
  3. Basic Bash Shell Commands
  4. 15 Basic Unix Commands One Must Know
Scroll to Top