Shell Scripts1
Shell Scripts1
sh
echo "enter 1st value"
read n1
echo "enter 2nd value"
read n2
r=$(expr $n1 + $n2)
echo "Result of expr: $r"
r=$(echo "$n1 + $n2" | bc)
echo "Result of bc: $r"
2. if-else.sh
#!/bin/bash
echo "enter a number"
read n1
echo "enter another number"
read n2
if [ $n1 -gt $n2 ]; then
echo "$n1 is greater than $n2"
else
echo "$n2 is greater than $n1"
fi
3. if-elif-else.sh
#!/bin/bash
#Find greatest among three numbers
echo "enter 1st number"
read n1
echo "enter 2nd number"
read n2
echo "enter 3rd number"
read n3
if [ $n1 -gt $n2 ] && [ $n1 -gt $n3 ]; then
echo "$n1 is greatest"
fi
4. addition.sh
echo "enter 1st number"
read n1
echo "enter 2nd number"
read n2
result=$(expr $n1 + $n2)
#result=$(echo "$n1 + $n2" | bc)
echo "result of summation is:$result"
5. addition1.sh
read n1
read n2
result=$(echo "$n1 + $n2" | bc) # Adds 5.5 and 3.2
echo "Result: $result"
6. for1.sh
# Example 1: Loop through a range of numbers
for i in 1 2 3 4 5
do
echo -n "Iteration: $i "
done
echo
7. nestedloop.sh
#Nested while Loop (Multiplication Table for numbers 1 to 3)
i=1
while (( i <= 3 )); do
j=1
while (( j <= 10 )); do
echo -n "$((i * j)) " # Print on same line
((j++))
done
echo # New line
((i++))
done
8. nestedloop_pattern1.sh
#Printing a Star Pattern
rows=5
for ((i=1; i<=rows; i++)); do
for ((j=1; j<=i; j++)); do
echo -n "* "
done
echo
done
9. case1.sh
#!/bin/bash
# Script to demonstrate Case Structure
echo "Enter a number between 1 and 3:"
read num
case $num in
1) echo "You selected One." ;;
2) echo "You selected Two." ;;
3) echo "You selected Three." ;;
*) echo "Invalid selection. Please enter a number between 1 and 3."
;;
esac
10. until.sh
# Script to demonstrate until
count=1
until [ $count -gt 5 ]
do
echo -n "Count: $count"
((count++))
done
echo ""
#another way
count=1
until (( count > 5 ))
do
echo "Count: $count"
((count++))
done
11. fibonacci_series.sh
a=0
b=1
echo "enter no. of terms"
read n
for ((i=0;i<n;i++))
do
c=$(expr $a + $b)
echo -n "$a "
a=$b
b=$c
#echo -n "$a "
done
12. while2.sh
# Script to demonstrate while loop
i=1
while [ $i -le 5 ]; do
echo -n "Iteration $i "
i=$((i + 1))
done
echo ""
#Example:
13. while1.sh
count=1
while [ $count -le 5 ]
do
echo "Count: $count"
((count++))
done
# Directory to list files from (you can change this to any directory)
DIRECTORY="/home/anurag"