Capturing User Input

One of the most important things you can do with your script is prompt a user for input, then capture that input for your use.


Using the read command to capture user input

Frequently you will need to ask a user for some kind of input. Within a running script, for instance, you may ask for information:

echo “Please enter name of the binary file to copy to your local directory.”

The user is expected to type in that file name, then press the Enter key. Their input is available to you as long as you capture it immediately:


Now you can, for instance, echo it back:


Or you can do something with that information:

cp /bin/$FILENAME ~/

It’s important to be clear what FILENAME holds: the name of the file, not the actual file.


You may want to use something that looks more like a system prompt:

echo -n “Enter the name of an animal: “

Note the use of the -n option to prevent a new line after the echo command.


Open your script

Prompt the user for their name, then greet them before running the original lines of the script.

Run the script using your name.

Now run the script using a pseudo-name with a space in it. What happens?


Debug Hint: During development, you should consider echoing values back whenever they are entered, in order to confirm that you’re getting what you expect.

Now is the time to test values with spaces in them to make sure your script handles them properly!