Skip to content

Input_output

This chapter covers input/output operations in bash, including reading from stdin, writing to stdout/stderr, file redirection, and advanced I/O techniques. These skills are essential for creating interactive scripts, processing data, and handling errors in DevOps workflows.


echo_basic.sh
#!/usr/bin/env bash
# Basic output
echo "Hello, World!"
# Without newline
echo -n "No newline: "
# Enable escape sequences
echo -e "Line1\nLine2"
# Print literal
echo -E "No expansion: \n"
printf_basic.sh
#!/usr/bin/env bash
# Basic printf
printf "Hello %s\n" "World"
# Format specifiers
printf "%d %s %.2f\n" 42 "answer" 3.14159
# Width and padding
printf "|%10s|\n" "hello"
printf "|%-10s|\n" "hello"
printf "|%05d|\n" 42

read_basic.sh
#!/usr/bin/env bash
# Basic read
echo "Enter your name:"
read name
echo "Hello, $name"
# Read with prompt
read -p "Enter your name: " name
echo "Hello, $name"
# Read with timeout
read -t 3 -p "Enter value (3s timeout): " value
echo "Value: $value"
read_array.sh
#!/usr/bin/env bash
# Read line into array
echo "Enter fruits (space-separated):"
read -a fruits
echo "You entered: ${fruits[@]}"
echo "First fruit: ${fruits[0]}"

read_file.sh
#!/usr/bin/env bash
# Method 1: While loop
while IFS= read -r line; do
echo "Line: $line"
done < /etc/passwd
# Method 2: Using cat
cat /etc/passwd | while read line; do
echo "Line: $line"
done
# Method 3: Using mapfile
mapfile -t lines < /etc/passwd
for line in "${lines[@]}"; do
echo "Line: $line"
done
write_file.sh
#!/usr/bin/env bash
# Overwrite file
echo "Content" > file.txt
# Append to file
echo "More content" >> file.txt
# Using printf
printf "%s\n" "Line 1" "Line 2" > output.txt

redirection.sh
#!/usr/bin/env bash
# Redirect stdout to file
echo "Output" > output.txt
# Redirect stderr to file
command 2> error.log
# Redirect both to same file
command &> all.log
# Redirect and append
echo "More" >> output.txt
# From file to command
command < input.txt
here_string.sh
#!/usr/bin/env bash
# Here string
read -r word <<< "hello world"
echo "$word" # hello
# Here document
cat << EOF
This is a multi-line
string that preserves
formatting
EOF

menu.sh
#!/usr/bin/env bash
show_menu() {
echo "1. View status"
echo "2. Start service"
echo "3. Stop service"
echo "4. Exit"
}
while true; do
show_menu
read -p "Choice: " choice
case "$choice" in
1) echo "Status: Running" ;;
2) echo "Starting service..." ;;
3) echo "Stopping service..." ;;
4) echo "Goodbye!"; break ;;
*) echo "Invalid choice" ;;
esac
echo
done
read_config.sh
#!/usr/bin/env bash
# Read key=value pairs
while IFS='=' read -r key value; do
# Skip comments and empty lines
[[ "$key" =~ ^# ]] && continue
[[ -z "$key" ]] && continue
echo "Setting: $key = $value"
declare "$key=$value"
done < config.txt
logging.sh
#!/usr/bin/env bash
LOG_FILE="/var/log/script.log"
log() {
local level="$1"
shift
local message="$*"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $message" | tee -a "$LOG_FILE"
}
log "INFO" "Script started"
log "WARN" "This is a warning"
log "ERROR" "This is an error"
confirm.sh
#!/usr/bin/env bash
confirm() {
local prompt="$1"
local response
while true; do
read -p "$prompt [y/n]: " response
case "$response" in
[yY]|[yY][eE][sS]) return 0 ;;
[nN]|[nN][oO]) return 1 ;;
*) echo "Please answer y or n" ;;
esac
done
}
if confirm "Continue with deployment?"; then
echo "Continuing..."
else
echo "Cancelled"
exit 1
fi

descriptors.sh
#!/usr/bin/env bash
# Open file descriptor
exec 3> output.txt
# Write to descriptor
echo "Line to fd 3" >&3
# Close descriptor
exec 3>&-
# Read from descriptor
exec 3< input.txt
read -u 3 line
echo "Read: $line"
exec 3<&-
tee_example.sh
#!/usr/bin/env bash
# Write to file and stdout
echo "Output" | tee file.txt
# Append
echo "More" | tee -a file.txt
# Multiple outputs
echo "Output" | tee file1.txt file2.txt

In this chapter, you learned about:

  • ✅ Basic output with echo and printf
  • ✅ Basic input with read
  • ✅ Reading and writing files
  • ✅ Redirection operators
  • ✅ Here strings and documents
  • ✅ Interactive menus
  • ✅ Configuration reading
  • ✅ Logging
  • ✅ File descriptors
  • ✅ tee command

  1. Create a script that asks for user input
  2. Write to a file using echo
  3. Read from a file line by line
  1. Implement an interactive menu
  2. Create a logging function
  3. Build a configuration file parser
  1. Implement file descriptor operations
  2. Create a confirmation prompt function
  3. Build a pipeline with tee

Continue to the next chapter to learn about functions.


Previous Chapter: String Manipulation Next Chapter: Functions