Skip to content

Input — Accepting User Input in Bash Scripts

Input allows Bash scripts to interact with users, accept command-line arguments, read data from files, and process information from standard input. Interactive scripts become more flexible because they can work with different values each time they are executed instead of relying on hardcoded data. Every Linux administrator, DevOps engineer, Cloud Architect, Platform Engineer, and Site Reliability Engineer (SRE) should understand how to safely collect and validate user input in production scripts.


Learning Path

Linux Mastery → Module 10: Bash Scripting → Lesson 6

Difficulty: Beginner → Intermediate

Reading Time: 80 Minutes

Course Progress

Course: Linux Mastery

Module: Bash Scripting

Lesson: 6 of 11


What You'll Learn

After completing this lesson, you'll be able to:

  • Read user input
  • Use command-line arguments
  • Display interactive prompts
  • Validate user input
  • Read passwords securely
  • Use default values
  • Process multiple inputs
  • Apply input handling in production scripts

Prerequisites

Complete:

  • Modules 1–9
  • Module 10 Lessons 1–5

Why Learn Input?

Imagine creating a user account script.

Without input:

useradd basha

The script creates only one user.

Using input:

read -p "Enter username: " USERNAME

useradd "$USERNAME"

The same script can create any user.


What is Input?

Input is data provided to a script.

It may come from:

  • User keyboard input
  • Command-line arguments
  • Files
  • Pipes
  • Other commands

Reading User Input

Basic syntax:

read VARIABLE

Example:

echo "Enter your name:"

read NAME

echo "Hello $NAME"

Reading with a Prompt

Instead of using echo, display the prompt directly.

read -p "Enter your city: " CITY

echo "$CITY"

Reading Multiple Values

read FIRST LAST

echo "$FIRST"

echo "$LAST"

Input:

John Doe

Output:

John

Doe

Reading Passwords

Hide user input while typing.

read -s -p "Password: " PASSWORD

echo

The password is not displayed on the screen.


Command-Line Arguments

Arguments are values passed when running a script.

Example:

./backup.sh /home

Inside the script:

echo "$1"

Output:

/home

Special Variables

Variable Description
$0 Script name
$1 First argument
$2 Second argument
$@ All arguments
$# Number of arguments
$$ Current process ID
$? Exit status of previous command

Checking Argument Count

if [ $# -lt 1 ]
then
    echo "Usage: ./script.sh <directory>"

    exit 1
fi

Loop Through Arguments

for ARG in "$@"
do
    echo "$ARG"
done

Using Default Values

NAME=${1:-Guest}

echo "Hello $NAME"

If no argument is supplied:

Hello Guest

Input Validation

Example:

read -p "Enter age: " AGE

if [[ "$AGE" =~ ^[0-9]+$ ]]
then
    echo "Valid"

else
    echo "Invalid"
fi

Confirm User Action

read -p "Continue? (y/n): " ANSWER

if [[ "$ANSWER" == "y" ]]
then
    echo "Continuing..."
else
    echo "Cancelled."
fi

Reading a File

while read LINE
do
    echo "$LINE"
done < users.txt

Reading from a Pipe

echo "Linux" | while read VALUE
do
    echo "$VALUE"
done

Common Commands

Read input.

read NAME

Prompt user.

read -p "Enter value: " VALUE

Read password.

read -s PASSWORD

Display arguments.

echo "$@"

Argument count.

echo "$#"

Real Production Examples

Create user.

read -p "Username: " USER

sudo useradd "$USER"

Accept deployment environment.

ENVIRONMENT=${1:-development}

echo "$ENVIRONMENT"

Restart a service.

read -p "Service: " SERVICE

systemctl restart "$SERVICE"

Production Perspective

Input handling is commonly used in:

  • Deployment scripts
  • Backup automation
  • User management
  • Cloud provisioning
  • Infrastructure automation
  • Monitoring tools
  • Configuration scripts
  • Interactive administration utilities

Proper validation helps prevent errors and improves script reliability.


Hands-on Lab

Task 1

Read a user's name.

read -p "Enter your name: " NAME

echo "$NAME"

Task 2

Read multiple values.

read FIRST LAST

echo "$FIRST"

echo "$LAST"

Task 3

Read a password.

read -s -p "Password: " PASSWORD

echo

Task 4

Display the first argument.

echo "$1"

Run:

./script.sh Linux

Task 5

Display all arguments.

echo "$@"

Task 6

Display the argument count.

echo "$#"

Task 7

Validate numeric input.

read AGE

if [[ "$AGE" =~ ^[0-9]+$ ]]
then
    echo "Valid"
else
    echo "Invalid"
fi

Task 8

Read a file line by line.

while read LINE
do
    echo "$LINE"
done < users.txt

Command Deep Dive

Command Purpose Production Example
read Read user input Interactive scripts
read -p Display prompt User-friendly input
read -s Read password Secure authentication
$1, $2 Command-line arguments Deployment scripts
$@ All arguments Batch processing
$# Number of arguments Input validation

Common Input Mistakes

Mistake Solution
Not validating input Always validate
Assuming arguments exist Check $#
Displaying passwords Use read -s
Forgetting quotes Quote variables
Hardcoding values Accept user input

Production Troubleshooting Scenario

Scenario

A deployment script fails because no environment name is supplied.

Before:

kubectl apply -f "$1"

If no argument is passed:

No such file

Improved:

if [ $# -lt 1 ]
then
    echo "Usage: ./deploy.sh <manifest>"

    exit 1
fi

The script now validates input before execution.


Best Practices

  • Validate all user input.
  • Check command-line arguments before use.
  • Use secure password input with read -s.
  • Quote variables to prevent word splitting.
  • Provide meaningful prompts.
  • Display usage information for missing arguments.
  • Handle invalid input gracefully.

Common Mistakes

❌ Assuming users always provide valid input.

✅ Verify users always provide valid input instead of assuming it.


❌ Not checking command-line arguments.

✅ Always checking command-line arguments.


❌ Displaying passwords on the terminal.

✅ Avoid this mistake: displaying passwords on the terminal.


❌ Forgetting to quote input variables.

✅ Remember to to quote input variables.


❌ Proceeding without validating required values.

✅ Avoid this mistake: proceeding without validating required values.


Interview Questions

Beginner

  1. What does the read command do?
  2. What is $1?
  3. What does $# represent?
  4. How do you securely read a password?

Intermediate

  1. What is the difference between keyboard input and command-line arguments?
  2. How do you validate user input?
  3. What does $@ represent?
  4. How do you provide default values for missing arguments?

Architect Level

  1. How would you design secure interactive Bash scripts?
  2. Why is input validation important in production automation?
  3. How can improper input handling create security risks?

Summary

In this lesson, you learned:

  • Reading user input
  • Interactive prompts
  • Command-line arguments
  • Password input
  • Input validation
  • Default values
  • Reading from files
  • Production scripting best practices

Input handling enables Bash scripts to interact with users and accept dynamic data. By validating input and handling errors gracefully, you can build secure, reliable, and production-ready automation scripts.


Key Takeaways

  • Use read to accept keyboard input.
  • Use command-line arguments for script flexibility.
  • Validate all user-provided data.
  • Use read -s for passwords.
  • Check $# before accessing arguments.
  • Provide meaningful prompts and usage messages.

What's Next?

Exit Codes — Understanding Command Success and Failure in Bash

You'll explore:

  • What exit codes are
  • Standard Linux exit codes
  • Using the exit command
  • Checking command status
  • Using $?
  • Returning exit codes from functions
  • Production error handling

By the end of the lesson, you'll be able to use exit codes effectively to build reliable Bash scripts that detect failures, communicate status, and integrate seamlessly with automation tools and CI/CD pipelines.