How to use 'read' command?

QuestionsQuestions8 SkillsProShell FunctionsOct, 27 2025
086

The read command in Bash is used to take input from the user. It reads a line of input from standard input (usually the keyboard) and assigns it to a variable. Here’s how to use the read command effectively:

Basic Syntax:

read variable_name

Example Usage:

  1. Single Variable Input:

    echo "Enter your name:"
    read name
    echo "Hello, $name!"
  2. Multiple Variables:
    You can read multiple values into separate variables by providing them in a single line:

    echo "Enter your first and last name:"
    read first_name last_name
    echo "Hello, $first_name $last_name!"
  3. Using Prompts:
    You can use the -p option to display a prompt directly:

    read -p "Enter your age: " age
    echo "You are $age years old."
  4. Silent Input:
    To read input silently (useful for passwords), use the -s option:

    read -sp "Enter your password: " password
    echo
    echo "Password entered."
  5. Timeout:
    You can set a timeout for the input using the -t option:

    read -t 10 -p "Enter your input (you have 10 seconds): " user_input
    if [ $? -eq 0 ]; then
        echo "You entered: $user_input"
    else
        echo "Input timed out."
    fi

Summary:

  • The read command is versatile and can be used to capture user input in various ways.
  • You can customize prompts, read multiple values, and control input visibility and timeouts.

0 Comments

no data
Be the first to share your comment!