Showing posts with label how to write bash script. Show all posts
Showing posts with label how to write bash script. Show all posts

03 December 2012

Shell Script to find factorial of a number using Recursion

2 comments

Q. How do I find factorial of a number using recursion function in Bash


Ans:

#!/bin/bash
#Recursive factorial function
factorial()
{
local=$1
if((local<=2)); then
echo $local
else
f=$((local -1))
#Recursive call
f=$(factorial $f)
f=$((f*local))
echo $f
fi
}
#main script
read -p "Enter the number:" n
if((n==0)); then
echo 1
else
#calling factorial function
factorial $n
fi
Read More...

30 November 2012

Shell Script to find "a" to the power "b" using function

1 comment

Q. How do I write Shell Script function to find "a" to the power "b"


Ans.

#!/bin/bash
#function to find "a" to the power "b"
power()
{
num=$1
pow=$2
counter=1
result=1
if((pow==0)); then
result=1
fi
if ((num==0)); then
result=0
fi
if((num>=1&&pow>=1)); then
while((counter<=pow))
do
result=$((result*num))
counter=$((counter + 1))
done
fi
#Printing the result
echo "$1 to the power $2 is $result"
}

#main script
read -p "Enter number:" num
read -p "Enter power:" pow

#calling above function
power $num $pow
Read More...

23 November 2012

Shell Script to reverse a String

8 comments

Q: How do I reverse a string in Linux/Unix?


Ans:

#!/bin/bash
read -p "Enter string:" string
len=${#string}
for (( i=$len-1; i>=0; i-- ))
do
# "${string:$i:1}"extract single single character from string.
reverse="$reverse${string:$i:1}"
done
echo "$reverse"
Read More...

05 November 2012

Shell Script to Print Fibonacci Series

1 comment

Q. How do I print fibonacci series in Bash


Ans:

#!/bin/bash
c=0
a=1
b=1
read -p "Enter limit of fibonacci Series:" n
echo -n "$a "
echo -n "$b "
#Fibonacci series logic
while((c<n))
do
c=$((a+b))
echo -n "$c "
a=$b
b=$c
done
echo -e "\n"
Read More...