5

I know that I can re-direct stdout and stderr from a script to a file such as follows, if this is executed directly on the command line :

sh myscript1.sh &>output.txt &

However if I place the above command to be executed inside another bash script in the same folder, instead of using the command line, it doesn't work.

I get the stdout and stderr on the terminal and the output.txt never gets written to. Why is this, and how do I solve it?

Engineer999
  • 1,151
  • Possible duplicate of https://unix.stackexchange.com/questions/61931/redirect-all-subsequent-commands-stderr-using-exec – Rui F Ribeiro Feb 14 '19 at 18:57

1 Answers1

7

Note that &> is a redirection operator that is specific to bash. You seem to use sh to execute scripts from the command line (not relying on the #!-line in the script itself). If you did that to a script that uses &>, it is definitely not guaranteed to work as /bin/sh may not be bash.

Instead, for a portable way of redirecting both standard output and standard error, use

./myscript.sh >output.txt 2>&1

Or, if you do want to use the &> redirection (and/or other bash-specific things), use bash scriptname to execute the bash script, or make sure that the script has a proper #!-line pointing to the bash executable, is executable, and then run the script as ./scriptname.


In a non-bash shell, utility &>file would be the same as

utility & >file

which is the same as

utility &
>file

which would start utility in the background, and then create an empty file called file (or truncate file if it already existed). There is no error in that command, it just doesn't do what a bash user might expect.

Kusalananda
  • 333,661
  • Thank you. However ./myscript.sh >output.txt 2>&1 &, this just wrote ./myscript.sh to output.txt. Strange as I have #!/bin/sh at the beginning of myscript.sh so it should have executed – Engineer999 Feb 14 '19 at 19:03
  • @Engineer999 Huh? That makes no sense at all. Did you say that it wrote the string ./myscript.sh into output.txt? Did you put echo in front of that or something? – Kusalananda Feb 14 '19 at 19:09