0% found this document useful (0 votes)
2 views3 pages

Unix Shell Scripts Lab

Uploaded by

rohit7585971500
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Unix Shell Scripts Lab

Uploaded by

rohit7585971500
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIX SHELL SCRIPTING LAB (Loops & Arrays)

Steps to Run a Shell Script:


1. Open terminal.
2. Create a script file using: vi [Link]
3. Write the script inside the file.
4. Save and exit (press ESC, type :wq).
5. Give execute permission: chmod +x [Link]
6. Run the script using: ./[Link]

1. Print numbers from 1 to N


#!/bin/bash
read n
for ((i=1;i<=n;i++))
do
echo $i
done

2. Sum of first N numbers


#!/bin/bash
read n
sum=0
for ((i=1;i<=n;i++))
do
sum=$((sum+i))
done
echo "Sum = $sum"

3. Factorial using loop


#!/bin/bash
read n
fact=1
for ((i=1;i<=n;i++))
do
fact=$((fact*i))
done
echo "Factorial = $fact"

4. Reverse a number
#!/bin/bash
read n
rev=0
while [ $n -gt 0 ]
do
r=$((n%10))
rev=$((rev*10+r))
n=$((n/10))
done
echo "Reverse = $rev"

5. Check palindrome
#!/bin/bash
read n
temp=$n
rev=0
while [ $n -gt 0 ]
do
r=$((n%10))
rev=$((rev*10+r))
n=$((n/10))
done
if [ $temp -eq $rev ]
then
echo "Palindrome"
else
echo "Not Palindrome"
fi

6. Fibonacci series
#!/bin/bash
read n
a=0
b=1
for ((i=0;i<n;i++))
do
echo -n "$a "
fn=$((a+b))
a=$b
b=$fn
done

7. Sum of array elements


#!/bin/bash
arr=(1 2 3 4 5)
sum=0
for i in ${arr[@]}
do
sum=$((sum+i))
done
echo "Sum = $sum"

8. Largest element in array


#!/bin/bash
arr=(10 20 5 40 30)
max=${arr[0]}
for i in ${arr[@]}
do
if [ $i -gt $max ]
then
max=$i
fi
done
echo "Max = $max"

9. Count elements in array


#!/bin/bash
arr=(a b c d e)
echo "Count = ${#arr[@]}"

10. Display array elements


#!/bin/bash
arr=(apple banana mango)
for i in ${arr[@]}
do
echo $i
done

11. Even numbers from array


#!/bin/bash
arr=(1 2 3 4 5 6)
for i in ${arr[@]}
do
if [ $((i%2)) -eq 0 ]
then
echo $i
fi
done

12. Search element in array


#!/bin/bash
arr=(10 20 30 40)
read key
found=0
for i in ${arr[@]}
do
if [ $i -eq $key ]
then
found=1
fi
done

if [ $found -eq 1 ]
then
echo "Found"
else
echo "Not Found"
fi

You might also like