Web Analytics

Reading Input

Intermediate~20 min read

Read interactive input and files using read, handle spaces safely with -r and IFS, and collect words into arrays.

read Basics

Output
Click Run to execute your code
Note: Use -r to prevent backslash escapes, and always quote variables when echoing user input.
Pro Tip: Set IFS=, (or another delimiter) temporarily for CSV-style parsing.
Caution: read without -r may treat backslashes specially and surprise you.

Advanced Reads

Output
Click Run to execute your code

Common Mistakes

1) Unquoted variables

# Wrong
echo $name
# Correct
echo "$name"

2) Forgetting -r

# Wrong
read line   # backslashes get consumed
# Correct
read -r line

Exercise: Parse CSV

Task: Read a name,age,city line and echo fields on separate lines.

Output
Click Run to execute your code
Show Solution
IFS=, read -r name age city
printf '%s\n' "$name" "$age" "$city"

Summary

  • Use read -r to read lines safely.
  • Temporarily set IFS to split on custom delimiters.
  • Loop with while IFS= read -r for files.

What's Next?

Redirect outputs and manage file descriptors in Output Redirection.