Pages

Ads 468x60px

Monday, July 23, 2012

Linux: Bash Shell Scripting

It will help you to understand Linux bash shell scripting.

Factorial Program
Save this program in a file and it should be an executable file. Run it from terminal like ./file_name


#!/bin/bash
echo -n "enter the number to calculate factorial:"
read number

input=$number;
fact=1;

if [ "$input" -eq "0" ]
then
echo -n "factorial of $input is $fact"
exit 1
else
while [ "$input" -ge "1" ]
do
let "fact =$input * $fact"

input=$((input-1))
done
fi
echo -n "factorial of $number is $fact"

Array Program

Save this program in a file and it should be an executable file. Run it from terminal like ./file_name

#!/bin/bash
echo "enter length of array"
read len1;
declare -a arr;
declare -a arr2;
i=0;
while(("$i" < "$len1"))
do
read num1;
arr[$i]=$num1;
i=$((i+1));
done

echo "2nd array"
j=0;
while(("$j" < "$len1"))
do
read num;
arr2[$j]=$num;
j=$((j+1));
done

echo "Arrays multiplication result is "
k=0;

while(("$k" < "$len1"))
do
 let "res = ${arr[$k]} * ${arr2[$k]}"
 k=$((k+1));
 echo "$res"
done

No comments:

Post a Comment