Input/output (I/O) operations are core to interacting with users and handling data in Linux shell scripting. Effective I/O handling allows scripts to receive input dynamically, display outputs clearly, and interact meaningfully with users or other software components.
Shell scripting provides simple yet flexible commands for reading input, printing output, and redirecting data streams, enabling automation and interactive usage scenarios.
Gathering User Input
The following are common methods for collecting input from users in shell scripts. They allow scripts to interact dynamically with users.
1. The read Command: The most common method to capture user input from the terminal.
Basic syntax:
read variable_nameIt pauses the script and waits for input, storing it in the specified variable.
Example:
echo "Enter your name:"
read name
echo "Hello, $name!"2. Using read with Prompt: The -p option allows displaying prompt text inline.
read -p "Enter your age: " age
echo "You are $age years old."3. Reading Multiple Variables: Accepts multiple space-separated inputs.
read first last
echo "First Name: $first, Last Name: $last"4. Silent Input (-s): Useful for passwords or sensitive information.
read -sp "Enter password: " password
echo
echo "Password entered!"5. Timeout for Input (-t): Reads input with a timeout in seconds.
read -t 10 -p "Enter choice within 10 seconds: " choice
echo "You selected: $choice"Displaying Output
Below are the standard tools for displaying script output. They allow clear and readable communication with users.
1. The echo Command: The simplest way to output text or variable values to the terminal.
echo "Hello, World!"
echo "User input was: $name"2. Options for echo: -e enables interpretation of backslash escapes:
echo -e "Line1\nLine2"3. The printf Command: Provides better control over formatting similar to C's printf.
Syntax example:
printf "Name: %s\nAge: %d\n" "$name" "$age"Does not add a newline automatically, so it must be included (\n).
Redirecting Input and Output
The following are tools used to connect and redirect command data. They allow chaining and filtering of outputs.
1. Standard Streams:
1. STDIN (standard input) - File descriptor 0
2. STDOUT (standard output) - File descriptor 1
3. STDERR (standard error) - File descriptor 2
2. Output Redirection (> and >>):
echo "Hello" > file.txtecho "World" >> file.txt3. Input Redirection (<): Reads input from a file instead of terminal:
sort < unsorted.txt4. Pipes (|): Connect the output of one command to the input of another:
ls -l | grep ".txt"5. Redirecting STDERR:
command 2> error.logcommand > output.log 2>&1
We have a sales campaign on our promoted courses and products. You can purchase 1 products at a discounted price up to 15% discount.