I am trying to write a script which is POSIX compliant, so it can run on any *nix system (Debian, Fedora, CentOS, AIX, Arch... ALL of them). When it comes to redirection, I am rather confused on what is supported by POSIX and what is not.
If I redirect ls -l file missingfile &> out.txt this works perfectly in bash. The line from stderr complaining that missingfile doesn't exist, and the permissions output from file, are both in out.txt. However, I believe this is only working because these shells support more than just POSIX standard operators. Upon researching this question I've come across conflicting answers.
This stackexchange answer, for example, seems to imply that &>, >&, >>& and &>> are non-standard operations. However, this answer explicitly states that some-program > some_file 2>&1 is POSIX compliant. Does this mean that the >& operator (using digits for stderr & stdout) is POSIX compliant whereas using &> to auto redirect both stderr and stdout to a file is not POSIX compliant? Or are both &> and >& not POSIX compliant / POSIX compliant (one of these two people are wrong)?
I considered just avoiding the & sign completely and using ls -l file missingfile >out.txt 2>out.txt however this comes with its own issue. Running the ls command this way causes the shell to open two file handles for out.txt, both pointing to offset 0 in the file. So when ls looks for these two files, one of the messages gets clobbered.
What one would expect ls -l file missingfile >out.txt 2>out.txt to output:
-rw-r--r-- 1 blah blah 0 Jun 3 13:18 file
ls: cannot access 'missingfile': No such file or directory
What is actually output:
-rw-r--r-- 1 blah blah 0 Jun 3 13:18 file
le or directory
What is the best way to redirect both stdout and stderr to a file in a POSIX compliant fashion?
&> out.txtdoesn't work in Dash. It does in Busybox sh, though, along with Bash and Zsh.shcommand even simply among versions of the same operating system in some cases.dashwhich is meant not to have any extension to POSIX standard. So if your script works in dash, it will work in bash, ksh, ash etc.