Saturday, March 5, 2016

BASH Shell Script Calculate Factorial by Reading From File and Passing data to Another script to Calculate


BASH Shell Scripts Run order:

</> List:
cleanFile.sh numberGenerator.sh factorialMain.sh factorial.sh

Details:

cleanFile.sh deletes all the contents of the file passed in the arguments.

numberGenerator.sh generates numbers based on the code and writes to specified file.

factorialMain.sh reads the file created by numberGenerator.sh line by line and passed the data read to factorial.sh to calculate and print result.

factorial.sh is a standalone script. It can either use command line arguments passed to calculate factorial or if no arguments was passed then asks to enter a number then prints its factorial.

These scripts can be modified to calculate other things or do file related tasks etc.
 

Codes:


cleanFile.sh

#!/bin/bash
# Delete all the data in the passed argument file.
echo "" > "$1"
view raw cleanFile.sh hosted with ❤ by GitHub

numberGenerator.sh

#!/bin/bash
# Generate numbers and save / append in the specified file.
generateNumbers(){
for (( c=1; c<=$1; c++ ))
do
echo $c >> numbers.txt
done
}
generateNumbers $1

factorialMain.sh

#!/bin/bash
# Read from file and send data to another script to calculate.
readAndCalculateData(){
while read input
do
echo "sending $input to Calculate:"
bash factorial.sh $input
done < "$1"
}
readAndCalculateData

factorial.sh

#!/bin/bash
# Mainly a demonstration of various ways to do the same thing.
# Using passed in argument or read from terminal.
# Factorial calculation by reading data a file by another program
# and use the output from that program as a input of this program.
calculateFactorial(){
#check if any command line arguments were passed otherwise read input.
if [ -z $1 ]; then
echo "Enter number to find factorial:"
read n
else
n=$(( $1 ))
fi
#variables
f=1
i=1
#factorial calculation
if [ $n -eq 0 ]; then
echo "1"
else
while [ $i -le $n ]
do
f=$(( $f * $i ))
i=`expr $i + 1`
done
echo "Factorial of $n is: $f."
fi
}
calculateFactorial $1
view raw factorial.sh hosted with ❤ by GitHub

Run Instruction:


Run each file by first bringing up terminal ( Shortcut: ctrl + alt + t ), then type the following,
    bash scriptName.sh
Replace scriptName.sh with the actual script name such as, "factorialMain.sh". Also make sure to bring up terminal in the folder where the script is located, or cd to that directory then run the command.

In order to pass command line arguments just call the script as above and add space separated numbers to it. For example,
    bash factorial.sh 5
It will print the factorial of 5 which is 120.

No comments: