|
|
|
Shell provides several ways to read file contents. This example covers common file reading patterns. |
|
|
Create a sample file for demonstration: |
|
|
Read entire file with |
|
|
Read file into a variable: |
|
|
Read first N lines with |
|
|
Read last N lines with |
|
|
Read specific line range: |
|
|
Read file line by line with while loop: |
|
|
IFS= prevents leading/trailing whitespace stripping. -r prevents backslash interpretation. |
|
|
Process lines with line numbers: |
|
|
Read file and handle last line without newline: |
|
|
Read specific fields from each line: |
|
|
Read file into array (bash-specific shown later): |
|
|
Check if file exists before reading: |
|
|
Read from stdin: |
|
|
Read with timeout (bash/ksh feature): read -t 5 input # Wait 5 seconds max |
|
|
Read a single character: read -n 1 char # Bash-specific |
|
|
Read with prompt: read -p “Enter value: ” value # Bash-specific |
|
|
Count lines, words, characters: |
|
|
Read binary files (not recommended for text processing): |
|
|
Read compressed files: |
|
|
Read from URL (using curl or wget): |
|
|
Bash
Bash provides mapfile/readarray for reading into arrays: |
|
|
Read into array with process substitution: |
|
|
Read file descriptor directly: |
|
|
Read with grep filtering: |
|
|
Read random line: |
|
|
Cleanup |
|