1

I wrote this one liner in bash:

while read line; printf $line' '; do : ; done < someFile

and it seemed to go over the lines of the files fine, but then it went into an infinite loop typing spaces. I realized my mistake was putting the printf before the do instead of after, but I still don't understand what's going on in here. Why do I get an infinite loop?

1
  • Do not printf $line' ' which will most likely fail if the value of line starts with a dash (this is BTW a way to unintentionally break your infinite loop). Do printf '%s ' "$line" instead. Commented Feb 3, 2021 at 17:02

2 Answers 2

4

You've misplaced do. You want:

while read line; do printf "%s" "$line "; done < someFile

The way you've written it is valid, but the semantics are not what you expect.

while read line; printf $line' '; do : ; done < someFile

is reading the line and then printing it. The value returned by printf is evaluated to determine if the loop body is entered. Since printf succeeds, it enters the loop.

The general syntax is while {list of commands}; do {list of commands}; done The first list of commands is executed, and the result of the final command is evaluated to determine if the loop body is entered.

But it seems what you really want is:

tr \\n ' ' < someFile
Sign up to request clarification or add additional context in comments.

1 Comment

I know I misplaced the do, it's written in the question, but the explanation is helpful. Also the : is just a place holder here, I did other stuff with line in there
0

the correct syntax is

while read line; do printf $line' '; done  < someFile

try it ;)

if write in multi-line script if better to understand

#!/bin/bash   
while read line
do
  printf $line' '
done < SomeFile

1 Comment

you're right i saw the do error and i didn't read right after Usali I add IFS= option before read command to prevent leading/trailing whitespace from being trimmed - code while IFS= read -r line; do COMMAND_on $line; done code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.