4

I'm new to bash (ksh only up until now). I'm struggling with whitespace being striped from variables. I've read a number posts on bash's treatment of leading whitespace but I'm not sure how to correct it in my example.

echo "No space"         > x.tmp
echo "     Some space" >> x.tmp
cat x.tmp
cat x.tmp | while read line
do
   echo "$line" >> y.tmp
done
cat y.tmp

Output:

No space
     Some space
No space
Some space

What do I need to do to preserve the whitespace?

Thanks.

Richard
  • 51

1 Answers1

8

You need to do

while IFS= read -r line

Setting IFS to the empty string will preserve whitespace.
Using -r will preserve any backslash sequences in the text.


If performance is a concern, note that a while read loop is very slow in bash. If you want to slurp the input into lines, and memory consumption is not a problem, read the input into an array of lines:

mapfile -t lines < x.tmp
for line in "${lines[@]}"; do
    do_something_with "$line"
done
glenn jackman
  • 85,964