Taking inputs from user in a script
Here we will see how to take input from user in a script with the help of read command.
#!/bin/bash
read -p "First number:" value1
echo
read -p "Second number:" value2
echo
read -sn1 -p "Press any key to see the answer..."
let answer=$value1*$value2
echo -e "\n Result is: $answer"
sunny@sunny-workstation bin]$ ./6_read_command.sh
First number:44
Second number:34
Press any key to see the answer...
Result is: 1496
sunny@sunny-workstation bin]$
#!/bin/bash
- Lets try multiplication of two numbers which the user enters.
- What read does is ? It takes values by user on stdin.
- It prompt the user to input any value on stdin.
- -p is used to display a prompt.
read -p "First number:" value1
- This will give a prompt as "First number" and store the value in variable "value1"
echo
- Will display a blank line.
read -p "Second number:" value2
- This will give a prompt as "Second number" and store the value in variable "value2"
echo
- Will display a blank line.
read -sn1 -p "Press any key to see the answer..."
- Just to make it bit more interactive lets add one more thing.
- -s means silent mode that is if any value is pressed it will not be displayed on the screen like as in the password.
- -nX means how many characters.
- X here is one that is any key.
let answer=$value1*$value2
- Lets get these values multiplied and store the result in answer variable.
echo -e "\n Result is: $answer"
- This will get the result printed.
- Observed one thing in the last read command we haven't added any variable to save the input.
- But read still stores the value in some variable called $REPLY
- If we want to then we can overwrite the vaule of $REPLY by adding a variable.
- If you want to see what to entered to see the result then you can use echo $REPLY.
sunny@sunny-workstation bin]$ ./6_read_command.sh
First number:44
Second number:34
Press any key to see the answer...
Result is: 1496
sunny@sunny-workstation bin]$
Comments
Post a Comment