Essential Shell Scripting Examples for Linux Automation

Posted by Anonymous and classified in Computers

Written on in English with a size of 3.37 KB

1. Armstrong Number Checker

Write a shell script to check whether a given number is an Armstrong number.

echo "Enter a number"
read c
x=$c
sum=0
while [ $x -gt 0 ]
do
r=$(( $x % 10 ))
n=$(( $r * $r * $r ))
sum=$(( $sum + $n ))
x=$(( $x / 10 ))
done
if [ $sum -eq $c ]
then
echo "This is an Armstrong number"
else
echo "This is not an Armstrong number"
fi

2. Calculate Area of a Circle

Write a shell script to find the area of a circle.

echo "Enter radius"
read r
echo "Area is"
echo "3.14 * $r * $r" | bc

3. Average of Command Line Arguments

Write a shell script to find the average of numbers entered as command line arguments.

sum=0
for i in $*
do
sum=$((sum + i))
done
echo "Summation of $# numbers is: $sum"
N=$#
avg=$(echo "$sum / $N" | bc -l)
echo "Average = $avg"

4. Menu-Driven Calculator

Write a shell script to create a menu-driven calculator using case.

i="y"
echo "Enter first number:"
read n1
echo "Enter second number:"
read n2
while [ "$i" = "y" ]
do
echo "1. Add, 2. Sub, 3. Mul, 4. Div"
read ch
case $ch in
1) echo "Sum = $((n1 + n2))" ;;
2) echo "Sub = $((n1 - n2))" ;;
3) echo "Mul = $((n1 * n2))" ;;
4) echo "Div = $(echo "$n1 / $n2" | bc -l)" ;;
*) echo "Invalid choice" ;;
esac
echo "Do you want to continue (y/n)?"
read i
done

5. Compare and Remove Duplicate Files

Write a shell script to compare two files and remove one if they are identical.

echo -n "Enter file1: "
read file1
echo -n "Enter file2: "
read file2
if cmp -s -- "$file1" "$file2"
then
echo "Files are identical. Removing $file2..."
rm "$file2"
else
echo "Files are different."
fi

6. Count Lines, Words, and Characters

Write a shell script to count the number of lines, words, and characters in a file.

echo "Enter the filename"
read file
c=$(wc -c < "$file")
w=$(wc -w < "$file")
l=$(wc -l < "$file")
echo "Characters: $c, Words: $w, Lines: $l"

7. Calculate Factorial

Write a shell script to find the factorial of a given number.

echo "Enter the number"
read num
fact=1
while [ $num -gt 1 ]
do
fact=$((fact * num))
num=$((num - 1))
done
echo "Factorial = $fact"

8. Generate Fibonacci Sequence

Write a shell script to find n Fibonacci numbers.

echo "How many Fibonacci numbers do you want?"
read total
x=0; y=1; i=2
echo "$x"; echo "$y"
while [ $i -lt $total ]
do
z=$((x + y))
echo "$z"
x=$y; y=$z
i=$((i + 1))
done

9. Time-Based Greeting Script

Write a shell script that displays a greeting based on the current time.

check=$(date +%H)
if [ $check -ge 6 -a $check -lt 12 ]; then
echo "Good Morning"
elif [ $check -ge 12 -a $check -lt 16 ]; then
echo "Good Afternoon"
else
echo "Good Evening"
fi

Related entries: