0

I would like to redirect both the stdout and stderr of an executed file (file_1.txt) to another file (file_2.txt), and I would like to append this output to the file_2.txt contents. I have tried this:

$ ./file_1.txt >>&2 file_2.txt

That did not work. What am I doing wrong? What is the correct command?

1

If the shell is bash or ksh (version 2020.0.0 and perhaps in others), what you need is this:

./file_1.txt >> file_2.txt 2>&1 

That will redirect stderr to stdout which is being appended to file_2.txt. The & lets the shell know that you are working with file descriptors instead of file names. The command that you have doesn't work because the syntax isn't valid for anything and hence the redirection can't be parsed by the shell.

The command above takes care of this by redirecting both the file_2.txt as I explained.

If bash, you can also use, provided by steeldriver:

./file_1.txt &>> file_2.txt

That does the same thing. & means both stdout and stderr and >> appends them both the file_2.txt. I gave the first command initially because that's what I normally use due to it being what I learned first many years ago.

Neither works with tcsh version 6.21.00 after testing. They both give, respectively, Invalid null command. and Ambiguous output redirect.

6
  • 1
    In bash there's a semantic equivalent &>> file_2.txt which is perhaps what the OP was reaching for Aug 3 at 1:21
  • @steeldriver I've added that one to my answer for reference. I'd forgotten about it after always using the first. Aug 3 at 1:28
  • Thank you, Nasir and steeldriver, for these answers. Your explanation clarified the solution and educated me. In response to your question about what shell I am working on, it is bash. Many thanks, again. Much appreciated.
    – WildGTX
    Aug 3 at 1:39
  • >> file_2.txt 2>&1 is POSIX and Bourne syntax from the 70s. It's supported by all Bourne-like shells. (t)csh also support >>& file_2.txt since the 70s (that one also supported by zsh). In rc / es / akanga: >> file_2.txt >[2=1] Aug 3 at 5:18
  • Note that ksh2020 is a now abandoned attempt to create a community based version of ksh93 based on the last beta release from AT&T research (now disbanded). It's already been removed from some of the Linux distributions where it had been included for a short while such as Debian. For a still actively and community maintained version of ksh93, see github.com/ksh93/ksh (based on ksh93u+ the last "stable" version from AT&T). Aug 3 at 5:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.