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.

1

1 Answer 1

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
2
  • That did it. :-) I never would have thought of that. Thanks. Commented Apr 11, 2018 at 19:45
  • 3
    @Richard Good! If this solves your issue, please consider accepting the answer. Commented Apr 11, 2018 at 20:27

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.