Skip to content

Instantly share code, notes, and snippets.

@quickgrid
Created March 5, 2016 14:32
Show Gist options
  • Save quickgrid/0a3d42c09995a9aae859 to your computer and use it in GitHub Desktop.
Save quickgrid/0a3d42c09995a9aae859 to your computer and use it in GitHub Desktop.
Shell script for calculateing factorial with either reading user input from terminal or passed in arguments
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment