Problem Statement
Explain how to read user input and handle output in shell scripts including read command, echo, printf, and here documents.
Explanation
Read user input with read command: read VAR prompts for input and stores in VAR. Prompt with -p: read -p "Enter name: " NAME. Silent input (passwords): read -s PASSWORD. Read multiple variables: read VAR1 VAR2 splits input on whitespace. Read line with spaces: read -r LINE (raw mode prevents backslash interpretation). Timeout: read -t 5 times out after 5 seconds.
Advanced read: read array items with read -a ARRAY splitting into array, read from file with while IFS= read -r line; do echo "$line"; done < file.txt. Default variable: read without variable stores in $REPLY. Read with delimiter: read -d ':' VAR reads until colon. Handle empty input: read VAR || VAR="default".
Output with echo: echo "text" outputs with newline, echo -n "text" suppresses newline, echo -e "text\nmore" interprets escape sequences (\n, \t, etc.). Echo is simple but printf offers more control: printf "%s\n" "$VAR" formats output, printf "%-20s %d\n" "$NAME" "$AGE" formats columns with width specification, printf "%03d\n" 5 outputs 005 with zero padding.
Here documents for multi-line input: cat << EOF creates multi-line content until EOF delimiter. Expand variables: cat << EOF hello $USER EOF expands $USER. Prevent expansion: cat << 'EOF' or cat << \EOF. Common for generating config files: cat << EOF > config.txt content here EOF writes to file. Indent with <<-: cat <<- EOF strips leading tabs (not spaces).
Output redirection: echo "text" > file overwrites, echo "text" >> file appends. Tee for both file and stdout: echo "text" | tee file shows and saves. Redirect stderr: echo "error" >&2 sends to stderr. Suppress output: command > /dev/null 2>&1. Understanding input/output makes scripts interactive and handles data flow effectively.