Shell Script · User Input

Shell Scripting · Lesson 7

User Input

Take input from user using read command. Create interactive shell scripts. Validate user input. Build dynamic scripts based on user response.

What is User Input?

User input allows a script to accept values from the user during execution. This makes scripts interactive and dynamic.

In shell scripting, input is usually taken using the read command.

Why Use User Input?

Interactive Scripts

Allows users to provide values dynamically.

Reusable Scripts

One script can handle many scenarios using inputs.

Better UX

Makes scripts user-friendly and interactive.

Input Examples

1. Basic User Input

Use the read command to take input from the user.

terminal — bash
user-input
echo "Enter your name:"
read name
echo "Hello $name"

2. Using read with -p option

The -p option displays a prompt message on the same line.

terminal — bash
user-input
read -p "Enter your age: " age
echo "Your age is $age"

3. Reading Multiple Inputs

You can read multiple values in a single command.

terminal — bash
user-input
read -p "Enter first name and last name: " fname lname
echo "First Name: $fname"
echo "Last Name: $lname"

4. Silent Input (Password)

Use -s to hide input (useful for passwords).

terminal — bash
user-input
read -s -p "Enter password: " pass
echo
echo "Password stored successfully"

Best Practices

Follow These Tips

  • Always validate user input when possible.
  • Use -p to display clear prompts.
  • Use -s for sensitive input like passwords.
  • Avoid exposing sensitive data on screen.

Practice Task – User Input

  • Ask user for their name and age.
  • Print a greeting using the input.
  • Ask for password using silent input.
  • Display a success message.

Next lesson: Conditional Statements (if / else)