Bash User Input
In Bash scripts, many time we need to take some user inputs. We like to collect some information from user and use that information during script execution.
These interactive scripts are more global and flexible than normal scripts which contain static values for variables.
In bash, we have read command that used to collect user input and save it in variable for further use in script execution. Let’s see some of its examples to understand it in detail.
#!/bin/bash echo -n "please type you name :" read name echo "Welcome $name, in World of Bash scripting" ===================================== OutPut #./bash_read1.sh please type you name :Reader Welcome Reader, in World of Bash scripting
In above example, we used echo command for prompt interactive message and use read command for storing variable. Without echo it would not be possible to inform user for inputs. Whatever values we type will automatically assign
to variable “name” which was mention after read command. we can use as many as variables after read command. let’s see one examples for multiple variables values.
#!/bin/bash echo -n "please type you names :" read name1 name2 echo "Welcome $name1 and $name2, in World of Bash scripting" ===================================== OutPut #./bash_read1.sh please type you names :Reader1 Reader2 Welcome Reader1 and Reader2, in World of Bash scripting
In above examples, we tried to cover multiple variable in bash read command. we can see it is quit easy to use read command for single and multiple user inputs.
As we can see, we use echo for user interaction to display message for user, so that user provide input on same message. let’s try to remove it and use read command for same.
#!/bin/bash read -p "please type you name :" name Name echo "Welcome $name and $Name, in Bash script World" ===================================== OutPut #./bash_read2.sh please type you name :Reader Welcome Reader and , in Bash script World
Sometime we need to hide our input, like providing password. In read command there is provision to do that as well. in general terms we called stty echoed. we can replicate same with “stty -echo”.
But in read command it is quit easy to perform same thing.
#!/bin/bash read -p "please type you name :" name read -sp "please type your password :" password ; echo echo "Helo $name, thanks for providing your login details, we will take it further" ===================================== OutPut #./bash_read3.sh please type you name :Reader please type your password : Helo Reader, thanks for providing your login details, we will take it further