Linux Input Reading

LinuxBeginner
Practice Now

Introduction

This lab introduces you to input reading in Linux shell scripts. Input reading is a fundamental skill for creating interactive shell scripts that can respond to user input. By learning how to use the read command, you will be able to collect and process data entered by users, making your scripts more versatile and user-friendly.

In this lab, you will learn how to read user input, process that input within your scripts, and create interactive shell scripts that can respond dynamically to different user inputs. These skills are essential for writing effective command-line tools and scripts in Linux environments.

Basic Input Reading

The read command is a built-in shell command that reads a line of input from the standard input (usually the keyboard) and assigns it to variables. This enables scripts to receive and process user input.

In this step, you will create a simple script that reads user input and displays it back to the user.

  1. First, ensure you are in the project directory:

    cd /home/labex/project
  2. Create a new script file named input_reader.sh:

    touch input_reader.sh
  3. Make the script executable:

    chmod +x input_reader.sh
  4. Open the script file using the nano text editor:

    nano input_reader.sh
  5. Add the following code to the script:

    #!/bin/bash
    
    ## A simple script to demonstrate basic input reading
    echo "Please enter your name:"
    read name
    echo "Hello, $name! Welcome to Linux input reading."

    This script:

    • Begins with a shebang (#!/bin/bash) that specifies the script should run using bash
    • Displays a prompt asking for the user's name
    • Uses the read command to capture what the user types and stores it in a variable called name
    • Displays a greeting that includes the name entered by the user
  6. Save the file by pressing Ctrl+O, then press Enter to confirm the filename, and exit nano by pressing Ctrl+X.

  7. Run the script to test it:

    ./input_reader.sh

    You should see an output similar to this:

    Please enter your name:
    John
    Hello, John! Welcome to Linux input reading.

    The actual output will display whatever name you entered instead of "John".

The read command waits for user input and stores it in one or more variables. In this example, the input was stored in a single variable called name. Later, you will learn how to capture multiple inputs with a single read command.

Using Read with Loops

In this step, you will enhance your script to continuously read inputs using a loop until a specific exit condition is met. This pattern is commonly used in interactive scripts where you need to collect multiple pieces of information from the user.

  1. Open your script for editing:

    nano input_reader.sh
  2. Replace the existing content with the following code:

    #!/bin/bash
    
    ## Enhanced script with a loop for multiple inputs
    echo "Enter multiple inputs (type 'exit' to quit):"
    
    while true; do
      ## Prompt for input
      echo -n "> "
      read input
    
      ## Check if user wants to exit
      if [[ "$input" == "exit" ]]; then
        echo "Exiting the input reader."
        break
      fi
    
      ## Process the input
      echo "You entered: $input"
    done
    
    echo "Thank you for using the input reader!"

    This script:

    • Uses a while true loop to create an infinite loop that will keep accepting inputs
    • Displays a prompt (>) before each input using echo -n which prevents a newline
    • Reads user input into the input variable
    • Checks if the input is "exit" and breaks out of the loop if it is
    • Otherwise, it echoes the input back to the user
    • Finally, displays a thank you message after exiting the loop
  3. Save the file by pressing Ctrl+O, then press Enter to confirm the filename, and exit nano by pressing Ctrl+X.

  4. Run the enhanced script:

    ./input_reader.sh

    You should see an output similar to this:

    Enter multiple inputs (type 'exit' to quit):
    > hello
    You entered: hello
    > world
    You entered: world
    > exit
    Exiting the input reader.
    Thank you for using the input reader!

This loop structure is particularly useful when you need to process multiple inputs sequentially, such as when building a simple command-line interface or a data entry tool. The break statement is used to exit the loop when the user types "exit", but you could modify the condition to exit based on any criteria you need.

Reading with Prompts and Default Values

In this step, you will learn how to provide default values for input and use the -p option to create cleaner prompts. This is useful when you want to give users the option to simply press Enter to accept a suggested value.

  1. Open your script for editing:

    nano input_reader.sh
  2. Replace the existing content with the following code:

    #!/bin/bash
    
    ## Script demonstrating read with default values
    
    ## Using -p flag for prompt and providing default with || operator
    read -p "Enter your country (default: USA): " country
    country=${country:-USA}
    echo "Country set to: $country"
    
    ## Another example with a default value
    read -p "Enter your preferred programming language (default: Bash): " language
    language=${language:-Bash}
    echo "Programming language set to: $language"
    
    ## Combining with a timeout using -t option
    echo "Quick response needed:"
    read -t 5 -p "What is your favorite color? (You have 5 seconds, default: Blue): " color
    color=${color:-Blue}
    echo "Favorite color set to: $color"

    This script:

    • Uses the -p flag to display a prompt within the same read command, making the code more concise
    • Applies the ${variable:-default} syntax to set a default value if the user input is empty
    • Demonstrates the -t option, which sets a timeout for input (5 seconds in this example)
  3. Save the file by pressing Ctrl+O, then press Enter to confirm the filename, and exit nano by pressing Ctrl+X.

  4. Run the script to test it:

    ./input_reader.sh

    Try these scenarios:

    • Enter a country name when prompted, then press Enter
    • Just press Enter (without typing anything) to accept the default value
    • For the timeout example, try waiting longer than 5 seconds to see what happens

    Example output when accepting default values:

    Enter your country (default: USA):
    Country set to: USA
    Enter your preferred programming language (default: Bash):
    Programming language set to: Bash
    Quick response needed:
    What is your favorite color? (You have 5 seconds, default: Blue):
    Favorite color set to: Blue

The -p option to read allows you to provide a prompt in the same command, making your scripts cleaner and more readable. The ${variable:-default} syntax is a powerful shell feature that substitutes a default value when the variable is unset or empty, which is perfect for providing default options in scripts.

Reading Secure Input and Multiple Variables

In this final step, you will learn two more advanced techniques:

  1. Reading secure input (like passwords) without displaying the characters on screen

  2. Reading multiple variables with a single read command

  3. Open your script for editing:

    nano input_reader.sh
  4. Replace the existing content with the following code:

    #!/bin/bash
    
    ## Script demonstrating secure input and multiple variable reading
    
    ## Secure input reading with -s flag (no echo)
    echo "Secure Input Example:"
    read -p "Username: " username
    read -s -p "Password: " password
    echo ## Add a newline after password input
    echo "Username entered: $username"
    echo "Password length: ${#password} characters"
    
    ## Reading multiple variables at once
    echo -e "\nMultiple Variable Example:"
    read -p "Enter first name, last name, and age (separated by spaces): " first_name last_name age
    
    echo "First name: $first_name"
    echo "Last name: $last_name"
    echo "Age: $age"
    
    ## Reading with a custom delimiter
    echo -e "\nCustom Delimiter Example:"
    read -p "Enter comma-separated values: " -d "," value1
    echo ## Add a newline
    echo "First value before comma: $value1"
    
    echo -e "\nThank you for completing this lab on Linux input reading!"

    This script:

    • Uses the -s flag with read to hide the input (useful for passwords or other sensitive information)
    • Shows how to read multiple variables from a single line of input by providing multiple variable names to the read command
    • Demonstrates the -d flag to specify a custom delimiter (instead of the default newline character)
  5. Save the file by pressing Ctrl+O, then press Enter to confirm the filename, and exit nano by pressing Ctrl+X.

  6. Run the script to test it:

    ./input_reader.sh

    Example output (your inputs will be different):

    Secure Input Example:
    Username: john_doe
    Password:
    Username entered: john_doe
    Password length: 8 characters
    
    Multiple Variable Example:
    Enter first name, last name, and age (separated by spaces): John Doe 30
    First name: John
    Last name: Doe
    Age: 30
    
    Custom Delimiter Example:
    Enter comma-separated values: test,
    First value before comma: test
    
    Thank you for completing this lab on Linux input reading!

Security is important when handling sensitive information like passwords. The -s flag ensures that the characters typed are not displayed on the screen. Notice that in the password example, the script only shows the length of the password for verification, not the actual password.

Reading multiple variables at once can make your scripts more efficient and user-friendly. When the read command is given multiple variable names, it splits the input based on the IFS (Internal Field Separator) environment variable, which defaults to whitespace (spaces, tabs, and newlines).

The -d flag allows you to change the delimiter that signals the end of input. By default, read stops at a newline (when you press Enter), but you can change it to any character, like a comma in the example.

Summary

In this lab, you have learned key techniques for reading and processing user input in Linux bash scripts:

  1. Basic Input Reading: Using the read command to capture user input into variables.

  2. Loop-Based Input: Implementing loops to continuously read input until a specific condition is met.

  3. Default Values and Prompts: Setting default values for input and creating cleaner scripts with inline prompts.

  4. Advanced Techniques: Reading secure input without displaying it on screen, capturing multiple variables in a single command, and using custom delimiters.

These input reading skills are fundamental for creating interactive shell scripts that can adapt to user input, provide appropriate defaults, and handle various types of data. You can now apply these techniques to create more responsive and user-friendly command-line tools and scripts.

As you continue to develop your Linux skills, consider combining these input reading methods with other bash features such as conditional statements, functions, and file operations to create more complex and powerful tools for automation and system management.