Capturing User Input

  1. Unix Shell Scripting
  2. Shell Basics
  3. Testing in bash
  4. Capturing User Input
  5. Scripting : Exercise 1
  6. Debugging
  7. Bourne/Bash/Korn Commands
  8. Shell Variables
  9. IO Redirection
  10. Pipes
  11. Operators, Wildcards and Expressions
  12. Flow Control
  13. Scripting : Exercise 2
  14. Shell Differences
  15. String Functions
  16. awk
  17. xargs
  18. Power Tools
  19. Exercise 3

One of the most important things you can do with your script is prompt a user for input, then capture that user 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 file to copy."

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:

read filename

Now you can, for instance, echo it back:

echo $filename

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.


Create a script named .

Prompt the user for their name, then greet them.

Run the script using your name.

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

Introduction to Debugging

During development, you can watch what your script is doing line-by-line by using this syntax:

bash -v


bash -x

Try them both and note the differences.

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