Question

I have bash set to noclobber mode in my .bashrc - from the bash man page:

       set [--abefhkmnptuvxBCHP] [-o option] [arg ...]
...
              -C      If set, bash does not overwrite an existing  file  with
                      the  >,  >&, and  redirection operators.  This may be
                      overridden when creating  output  files  by  using  the
                      redirection operator >| instead of >.

Sometimes I want to override this behavior, so I use the >| redirection operator to do this. But sometimes I want to redirect both stdout and stderr to a file. The file may already exist, so I may want to clobber this file. Given the documented operators >& and >|, I would expect there also to be a >|& or >&| or &>| operator, which would redirect both stdout and stderr to the file, with a forceful overwrite. But I am unable to find such a single operator:

$ ls file.txt missing
ls: missing: No such file or directory
file.txt
$ ls file.txt missing >& output.txt
bash: output.txt: cannot overwrite existing file
$ ls file.txt missing >&| output.txt
bash: syntax error near unexpected token `|'
$ ls file.txt missing >|& output.txt
bash: syntax error near unexpected token `&'
$ ls file.txt missing &>| output.txt
bash: syntax error near unexpected token `|'
$ 

I know I can do this with a combination of >| and 2>&1, but would rather be able to do this with a single operator:

$ ls file.txt missing >| output.txt 2>&1
$ cat output.txt 
ls: missing: No such file or directory
file.txt
$ 

Does such an operator exist, documented or otherwise?


I notice that there appears to be a bit of a precedence to what I am asking about - specifically in the "append" versions of these operators. In bash 4, the &>> operator was introduced, which allows stdout and stderr to be appended to the output file. But there appears to be no "clobber" version of this. How can I redirect and append both stdout and stderr to a file with Bash?

Was it helpful?

Solution

I'm afraid not. You have to use the >|...2>&1 solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top