0

I can iterate through a file, a.txt, performing an arbitrary command (echo in this example) on each line by doing

xargs -n1 echo < a.txt

or

for a in $(cat a.txt); do echo $a; done

Why can I not do something like

for arg do echo $arg; done < a.txt

which returns success but no output?

7
  • 2
    change for arg to while read arg; and it should do what you want. Commented Jan 15, 2021 at 22:44
  • Thanks, and indeed it does. I'm just wondering if a for loop similar to the one above would work. and if not, why. Commented Jan 15, 2021 at 22:49
  • on each line by doing xargs -n1 will not work with lines that contain odd number of ' or/and odd number of ". or for a in $(cat a.txt) will not work with lines that has spaces or tabs between words. Commented Jan 15, 2021 at 22:49
  • 1
    for arg; do ... is equivalent to for arg in "$@"; do .... It does not take values from the input stream, but from the positional parameters. Commented Jan 15, 2021 at 22:53
  • 1
    don't read lines of a file with for Commented Jan 15, 2021 at 22:55

1 Answer 1

1

The for loop takes its iteration values from its in clause or from the content of $@; it does not read from stdin.

In your last example, the entire command's stdin is being redirected from a.txt and it produces no output because for doesn't read from stdin and its command block's commands don't either.

The read command, however, does read from stdin and that's why the while read arg; loop works.

Credit to Glenn for explaining the meaning of a for command without an in clause:

The value of $@ is empty and that is why your for loop produces no output. Redirecting a command's stdin from a file does not set $@. If you had placed that for loop in a script and executed it with some arguments, then your for loop would have printed the command line's arguments instead of the content of a.txt.

Sign up to request clarification or add additional context in comments.

2 Comments

for arg do ... implicitly uses the positional parameters, and is equivalent to for arg in "$@"; do
@glennjackman I was wondering why it produced nothing on stderr. Now I know.

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.