Skip to content
Advertisement

Does an argument after a redirection do anything?

Is any argument after a redirection ignored, or does it have any unintended consequences?

I was surprised to find that a typo I made in my bash script made absolutely no difference because it was specified after a redirect. E.g. I expected it to complain about something like this

./foo.sh > foo2.log whoops I made a typo

But it doesn’t throw any errors. I have to add a semi colon to actually get it to run as a command and error, something like

./foo.sh > foo2.log; whoops I made a typo

What surprised me even more, is that linux hasn’t given up after the redirect e.g.

./foo.sh > foo2.log whoops I made a typo > command_is_still_going.log

is absolutely fine and command_is_still_going.log is still created

Is the ‘whoops I made a typo’ argument completely ignored, or does it result in some unwanted behaviour? Since I tend to use this a lot.

Advertisement

Answer

Redirections are parsed and handled, then removed from the command-line. The remaining command-line is then executed. In other words, redirections can appear anywhere in the command-line. As a point of style you should put them at the end.

These are equivalent:

./foo.sh > foo2.log whoops I made a typo
./foo.sh whoops I made a typo > foo2.log 

If foo.sh ignores its arguments then “whoops I made a typo” has no effect.

Similarly, these are the same:

./foo.sh > foo2.log whoops I made a typo > command_is_still_going.log
./foo.sh whoops I made a typo > foo2.log > command_is_still_going.log

These are two separate commands:

./foo.sh > foo2.log; whoops I made a typo

./foo.sh > foo2.log
whoops I made a typo
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement