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?


1 Answer 1


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 &

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.

  • 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 Feb 14, 2019 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, 2019 at 19:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .