0

I'm running a loop on each line in a file.

if [ -e "/tmp/history" ]; then
  while read line; do
    connect.sh $line \
      && break
  done </tmp/history
fi

The file is formatted like:

user\ name user\ password

So that each line will contain $1 and $2 for connect.sh.

Yet it seems with my while loop $line loses the line breaks before passing to connect.sh so that user\ name becomes user name.

Is there a way I can modify my while loop to maintain the line breaks?

  • You're only reading into one variable here, but if you ever tried to split the line into $user and $password, you'd want to clear IFS. See https://unix.stackexchange.com/a/18936/117549 – Jeff Schaller Nov 22 '17 at 16:43
  • 1
    Also good reading: https://unix.stackexchange.com/q/169716/117549 – Jeff Schaller Nov 22 '17 at 16:43

1 Answers1

1

I was able to fix the problem by adding the -r flag and double quoting the variable.

if [ -e "/tmp/history" ]; then
  while read -r line; do
    connect.sh "$line" \
      && break
  done <"/tmp/history"
fi

Similar SO question.

  • 1
    If you want to preserve leading/trailing/interior whitespace, use while IFS= read -r line -- this is the idiomatic way to read lines of a file absolutely verbatim. – glenn jackman Nov 22 '17 at 16:55