Skip to content
Home » The Essential Tool for Interactive Input in Bash: read

The Essential Tool for Interactive Input in Bash: read

Have you ever needed to gather input from a user in your Bash script, but didn’t want to rely on command line arguments? If so, then the read command is your solution!

How read Works

read is a built-in command in Bash that allows you to gather input from a user. You can specify a prompt for the user to follow, and then store their input in a variable for later use in your script. Here’s an example of how you might use read:

echo "Enter your name:"
read name
echo "Hello, $name!"

When this script is run, the user will be prompted to enter their name, and then the script will greet them by name.

Surprising Fact: read Can Read from a File

You might not know this, but read can also read from a file! This can be useful if you have a list of inputs that you want to process in your script. Here’s an example of how you might use read to read from a file:

while read line
do
  echo "Processing line: $line"
done < input.txt

In this example, read will read each line of the input.txt file and store it in the line variable. The script will then process each line one by one.

5 Tips for Using read in Your Scripts

  1. Use read to gather input from a user in an interactive script.
  2. Use a prompt to guide the user in providing the correct input.
  3. Store the input in a variable for later use in your script.
  4. Use read to process a list of inputs from a file.
  5. Use read in a loop to process multiple inputs from the user or from a file.

Additional Resources

For more information on read, you can check out the Bash help and man pages:

  • help read
  • man read

Challenge: Create a Script that Uses read

Now that you know the basics of read, try creating a script that uses read to gather input from a user. You could create a simple script that asks the user for their name, age and then greets them, or you could create a more complex script that processes multiple inputs from the user or from a file.

Leave a Reply

Your email address will not be published. Required fields are marked *

18 + twelve =