In a previous Bash to Basics, I already showed how to print output to the terminal with the echo command. Today I'm going to show how to read input from the user and store it in a variable. We can then use that variable to print the text back to the terminal with the echo command.
First off, I like to create a directory to store my scripts. For the purpose of these posts I call it demo.
Next we're going to create the script. Open a text editor and enter the following:
#!/bin/bash # Program - readinput.sh # reads input from the user and prints it back to the terminal
That first line just tells the computer to run this script as a bash script, regardless of the shell environment that starts it. The other lines are comments. You can type anything there. It's just to explain the functionality of the program.
Now paste the following into your program:
echo Enter the text you want to print to the terminal:
This line prompts the user to provide input.
Add this line to your program:
This line tell the program to read some input and store it in a variable called userinput.
The following lines will print a blank line and then print back the user input text.
echo echo You entered: $userinput
The final line will the the program to end an report an error status of 0 (no errors).
Save the program as ~/demo/readinput.sh and close your text editor.
Now you need to make the program executable.
You can now run the program with: