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!
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
echo "Enter your 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.
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
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
readto gather input from a user in an interactive script.
- Use a prompt to guide the user in providing the correct input.
- Store the input in a variable for later use in your script.
readto process a list of inputs from a file.
readin a loop to process multiple inputs from the user or from a file.
For more information on
read, you can check out the Bash
Challenge: Create a Script that Uses
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.