Input parsing is a critical skill in shell scripting, enabling developers to efficiently process and manipulate input data. The Internal Field Separator (IFS) plays a crucial role in splitting input into multiple variables.
#!/bin/bash
## Default IFS parsing
IFS=' ' ## Space as delimiter
read -r name age city <<< "John Doe 30 New York"
echo "Name: $name, Age: $age, City: $city"
## Custom delimiter parsing
IFS=':'
read -r username password <<< "admin:secretpassword"
echo "Username: $username"
Parsing Technique |
Description |
Use Case |
Default IFS |
Splits on whitespace |
Simple space-separated inputs |
Custom IFS |
User-defined delimiters |
Complex input structures |
Read Options |
Advanced input control |
Specialized parsing needs |
## Multiple input parsing with custom delimiters
parse_csv() {
IFS=',' read -r col1 col2 col3 <<< "$1"
echo "Column 1: $col1"
echo "Column 2: $col2"
echo "Column 3: $col3"
}
parse_csv "data1,data2,data3"
graph TD
A[Input String] --> B{Parsing Method}
B --> |Default IFS| C[Whitespace Splitting]
B --> |Custom IFS| D[Custom Delimiter Splitting]
C --> E[Variable Assignment]
D --> E
The example demonstrates sophisticated input parsing techniques, highlighting the flexibility of bash input processing through IFS manipulation and read command variations.