While programming in shell scripting, you might encounter a situation where you need a response from the user. In that case, bash shell provides
read command which you can use for reading input from the user.
read variable OR read -p "Message" variable
Once you enter the response, the entered data is stored in the variable.
#Bash Shell script to find factorial of a number echo -n "Enter a number: " read number factorial=1 for(( i=1; i<=number; i++ )) do factorial=$[ $factorial * $i ] done echo "The factorial of $number is $factorial"
Output of the above program
Enter a number: 5 The factorial of 5 is 120
Explanation of the above code-
echo -n "Enter a number: " read number
When you use
-n option with
echo command, then newline character is not appended at the end of the string. By doing this, you enable the user to input data just after the string "Enter a number: ". After this, the user's response is stored in a
number variable. In case, you want to use
-p option of
read command then no need to write
echo command to display message. The above two lines can be replaced with the below single statement.
read -p "Enter a number: " number
factorial=1 for(( i=1; i<=number; i++ )) do factorial=$[ $factorial * $i ] done echo "The factorial of $number is $factorial"
for loop will iterate through all numbers from 1 to the entered number and stores the multiplication of each number in a