Linux

1) Find the sum of digits:

#!/bin/bash

number=$1
sum=0

while [ $number -gt 0 ]
do
    digit=$(( $number % 10 ))
    sum=$(( $sum + $digit ))
    number=$(( $number / 10 ))
done

echo “Sum of digits: $sum”

2) Find the average of numbers:

#!/bin/bash

sum=0
count=0

for num in “$@”
do
    sum=$(( $sum + $num ))
    count=$(( $count + 1 ))
done

average=$(echo “scale=2; $sum / $count” | bc)
echo “Average of numbers: $average”

3) Find the greatest of 3 numbers:

#!/bin/bash

max=$1

for num in “$@”
do
    if [ $num -gt $max ]
    then
        max=$num
    fi
done

echo “Greatest number: $max”

4)  Add two numbers provided at command line:

#!/bin/bash

sum=$(( $1 + $2 ))
echo “Sum of $1 and $2 is: $sum”

5) Find the factorial of a number:

#!/bin/bash

number=$1
factorial=1

while [ $number -gt 1 ]
do
    factorial=$(( $factorial * $number ))
    number=$(( $number – 1 ))
done

echo “Factorial of $1 is: $factorial”

6) Check if a given number is positive or negative:

#!/bin/bash

number=$1

if [ $number -gt 0 ]
then
    echo “$number is positive”
elif [ $number -lt 0 ]
then
    echo “$number is negative”
else
    echo “$number is zero”
fi

7) Shell program to find if a number is odd or even:

#!/bin/bash

number=$1

if [ $(( $number % 2 )) -eq 0 ]
then
    echo “$number is even”
else
    echo “$number is odd”
fi

8) Menu driven program:

#!/bin/bash

echo “Menu:”
echo “1. Find the sum of digits”
echo “2. Find the average of numbers”
echo “3. Find the greatest of 3 numbers”
echo “4. Add two numbers provided at command line”
echo “5. Find the factorial of a number”
echo “6. Check if a given number is positive or negative”
echo “7. Find if a number is odd or even”
echo “8. Exit”

read -p “Enter your choice: ” choice

case $choice in
    1)
        read -p “Enter a number: ” num
        ./sum_of_digits.sh $num
        ;;
    2)
        read -p “Enter numbers separated by space: ” nums
        ./average.sh $nums
        ;;
    3)
        read -p “Enter three numbers separated by space: ” num1 num2 num3
        ./greatest_of_three.sh $num1 $num2 $num3
        ;;
    4)
        read -p “Enter two numbers separated by space: ” num1 num2
        ./add_two_numbers.sh $num1 $num2
        ;;
    5)
        read -p “Enter a number: ” num
        ./factorial.sh $num
        ;;
    6)
        read -p “Enter a number: ” num
        ./positive_negative.sh $num
        ;;
    7)
        read -p “Enter a number: ” num
        ./odd_even.sh $num
        ;;
    8)
        echo “Exiting program”
        exit 0
        ;;
    *)
        echo “Invalid choice”
        ;;
esac

Leave a comment

Design a site like this with WordPress.com
Get started