Input_output
Chapter 14: Input/Output
Section titled “Chapter 14: Input/Output”Overview
Section titled “Overview”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.
Basic Output
Section titled “Basic Output”echo Command
Section titled “echo Command”#!/usr/bin/env bash# Basic outputecho "Hello, World!"
# Without newlineecho -n "No newline: "
# Enable escape sequencesecho -e "Line1\nLine2"
# Print literalecho -E "No expansion: \n"printf Command
Section titled “printf Command”#!/usr/bin/env bash# Basic printfprintf "Hello %s\n" "World"
# Format specifiersprintf "%d %s %.2f\n" 42 "answer" 3.14159
# Width and paddingprintf "|%10s|\n" "hello"printf "|%-10s|\n" "hello"printf "|%05d|\n" 42Basic Input
Section titled “Basic Input”read Command
Section titled “read Command”#!/usr/bin/env bash# Basic readecho "Enter your name:"read nameecho "Hello, $name"
# Read with promptread -p "Enter your name: " nameecho "Hello, $name"
# Read with timeoutread -t 3 -p "Enter value (3s timeout): " valueecho "Value: $value"Reading into Array
Section titled “Reading into Array”#!/usr/bin/env bash# Read line into arrayecho "Enter fruits (space-separated):"read -a fruits
echo "You entered: ${fruits[@]}"echo "First fruit: ${fruits[0]}"File I/O
Section titled “File I/O”Reading from File
Section titled “Reading from File”#!/usr/bin/env bash# Method 1: While loopwhile IFS= read -r line; do echo "Line: $line"done < /etc/passwd
# Method 2: Using catcat /etc/passwd | while read line; do echo "Line: $line"done
# Method 3: Using mapfilemapfile -t lines < /etc/passwdfor line in "${lines[@]}"; do echo "Line: $line"doneWriting to File
Section titled “Writing to File”#!/usr/bin/env bash# Overwrite fileecho "Content" > file.txt
# Append to fileecho "More content" >> file.txt
# Using printfprintf "%s\n" "Line 1" "Line 2" > output.txtRedirection
Section titled “Redirection”Input/Output Redirection
Section titled “Input/Output Redirection”#!/usr/bin/env bash# Redirect stdout to fileecho "Output" > output.txt
# Redirect stderr to filecommand 2> error.log
# Redirect both to same filecommand &> all.log
# Redirect and appendecho "More" >> output.txt
# From file to commandcommand < input.txtHere Strings and Here Documents
Section titled “Here Strings and Here Documents”#!/usr/bin/env bash# Here stringread -r word <<< "hello world"echo "$word" # hello
# Here documentcat << EOFThis is a multi-linestring that preservesformattingEOFPractical Examples
Section titled “Practical Examples”Example 1: Interactive Menu
Section titled “Example 1: Interactive Menu”#!/usr/bin/env bashshow_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 echodoneExample 2: Read Configuration
Section titled “Example 2: Read Configuration”#!/usr/bin/env bash# Read key=value pairswhile 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.txtExample 3: Logging
Section titled “Example 3: Logging”#!/usr/bin/env bashLOG_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"Example 4: Interactive Confirmation
Section titled “Example 4: Interactive Confirmation”#!/usr/bin/env bashconfirm() { 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 1fiAdvanced I/O
Section titled “Advanced I/O”File Descriptors
Section titled “File Descriptors”#!/usr/bin/env bash# Open file descriptorexec 3> output.txt
# Write to descriptorecho "Line to fd 3" >&3
# Close descriptorexec 3>&-
# Read from descriptorexec 3< input.txtread -u 3 lineecho "Read: $line"exec 3<&-tee Command
Section titled “tee Command”#!/usr/bin/env bash# Write to file and stdoutecho "Output" | tee file.txt
# Appendecho "More" | tee -a file.txt
# Multiple outputsecho "Output" | tee file1.txt file2.txtSummary
Section titled “Summary”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
Exercises
Section titled “Exercises”Level 1: Basics
Section titled “Level 1: Basics”- Create a script that asks for user input
- Write to a file using echo
- Read from a file line by line
Level 2: Intermediate
Section titled “Level 2: Intermediate”- Implement an interactive menu
- Create a logging function
- Build a configuration file parser
Level 3: Advanced
Section titled “Level 3: Advanced”- Implement file descriptor operations
- Create a confirmation prompt function
- Build a pipeline with tee
Next Steps
Section titled “Next Steps”Continue to the next chapter to learn about functions.
Previous Chapter: String Manipulation Next Chapter: Functions