Input/Output

Input and output operations in Bash

Reading user input

Different methods of reading user input

#!/bin/bash
# Basic input
read -p "Enter your name: " name
echo "Hello, $name!"

# Input with timeout
read -t 5 -p "Enter something (5 sec timeout): " input
if [ -n "$input" ]; then
    echo "You entered: $input"
else
    echo "Timeout or empty input"
fi

# Silent input (for passwords)
read -s -p "Enter password: " password
echo "Password entered (hidden)"
File input/output

File input and output operations

#!/bin/bash
# Write to file
echo "Line 1" > output.txt
echo "Line 2" >> output.txt

# Read from file
while IFS= read -r line; do
    echo "Read: $line"
done < output.txt

# Read file into array
mapfile -t lines < output.txt
echo "Array length: ${#lines[@]}"
Here documents

Using here documents for multi-line input

#!/bin/bash
# Here document
cat << EOF
This is a here document.
It can contain multiple lines.
Variables like $USER are expanded.
EOF

# Here document with no expansion
cat << 'EOF'
This text won't expand variables like $USER
EOF