The read
function allows us to prompt users for input and read that data from within a Bash script on Linux. In this tutorial, you will see multiple examples on how to read input from a Bash script.
Read Input From Bash Script Examples
Example 1. By using the read
command, you can read the input and store it in variables.
Script:
#!/bin/bash echo "Enter your name: " read name echo "Your name is $name"
Output:
$ ./example.sh Enter your name: Tux Your name is Tux
Example 2. By using the -p
option with read
, you don’t need to use the echo
command to ask users for input.
Script:
#!/bin/bash read -p "Enter your name: " name echo "Your name is $name"
Output:
$ ./example.sh Enter your name: Tux Your name is Tux
Example 3. With the -t
option, you can set a timeout. If the user doesn’t respond in time, the script will continue anyway. This example will wait for 60 seconds:
#!/bin/bash read -t 60 -p "Enter your name or wait 60 seconds: " name
Example 4. By putting the -s
flag, you can hide the user’s input. This should be used when asking for a password or other sensitive info.
Script:
#!/bin/bash read -p "Enter your name: " name read -sp "Enter password: " password echo -e "\n\nLogging into your account..." # more code
Output:
$ ./example.sh Enter your name: Tux Enter password: Logging into your account...
Example 5. You can accept multiple variables simultaneously by using a space between the words.
Script:
#!/bin/bash read -p "Enter your full name: " first_name middle_name family_name echo -e "\n\nWelcome, $first_name $middle_name $family_name !"
Output:
$ ./example.sh Enter your full name: Tux Linux Mascot Welcome, Tux Linux Mascot !