Menu
Coddy logo textTech

User Input In Scripts

Part of the Fundamentals section of Coddy's Terminal journey — lesson 69 of 82.

Variables are useful, but sometimes you want your script to ask the user for information while it runs. The read command pauses the script and waits for the user to type something, then stores that input in a variable.

Here's how it works:

#!/bin/bash
echo "What is your name?"
read name
echo "Hello, $name!"

When this script runs, it prints the question, waits for the user to type their name and press Enter, then greets them. The read command takes whatever the user types and stores it in the variable name.

You can make the prompt cleaner by using the -p flag, which combines the prompt message and input on the same line:

#!/bin/bash
read -p "Enter your name: " name
echo "Hello, $name!"

This displays Enter your name: and waits for input on the same line, which looks more polished. The -p flag takes the prompt text as its argument, followed by the variable name to store the input.

User input makes scripts interactive and adaptable. Instead of hardcoding values, you can write one script that works differently based on what the user provides each time they run it.

challenge icon

Challenge

Easy

Create a shell script called greeter.sh that asks the user for their favorite color and then displays a message using their input.

Your script should:

  1. Start with the shebang line (#!/bin/bash)
  2. Use read with the -p flag to prompt: What is your favorite color?
  3. Store the input in a variable called color
  4. Use echo to print: Nice! [color] is a great color! (where [color] is the user's input)

Make the script executable, then run it with blue as the input. This terminal is not interactive — it cannot stop and wait for you to type — so send the answer into the script with a pipe:

echo "blue" | ./greeter.sh

Your output should be:

Nice! blue is a great color!

Note: the What is your favorite color? prompt is not displayed here. read -p only prints its prompt when the input comes from a keyboard, and here it comes from the pipe.

Hint: Build the script line by line using echo with redirection. Use read -p "What is your favorite color? " color to prompt and capture input, then echo "Nice! $color is a great color!" to display the result.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals