Tuesday, December 28, 2021

[SOLVED] "&>>" in sh behaves differently in Ubuntu 16.04.2 and Fedora 24

Issue

Consider the following sh command:

sh -c 'sleep 3 &>> /dev/null'

&>> is supposed to redirect stdout and stderr. However, it is interpreted differently in Fedora 24 and Ubuntu 16.04.2.

In Fedora 24, it works exactly in this way, and the command above waits until sleep ends.

In Ubuntu 16.04.2, the command runs like sleep 3 & >> /dev/null, that is, sleep is sent to background and the command exits immediately.

The difference causes weired problems and cannot be easily found since I call things like foo arg1 arg2 output_file &>> test.log in a R script and expect the command ends with output_file is written. In Fedora 24, it works as expected but to my surprise the behavior changes in Ubuntu 16.04.2.

I'm not sure if this is a documented behavior.


Solution

The last link explains how to fix it for dash (the sh in Ubuntu):

sh -c 'sleep 3 > /dev/null 2>&1'

This will also work in Bash. Note the single > - you don't need to use the append operator (>>) with /dev/null.

Tip: Seeing this it might be tempting to write all your scripts to be compatible with both implementations of sh, but you'll only make your life unnecessarily difficult. Use the most powerful shell which you can expect to be available by default on all the platforms you're interested in. In your case this would be bash (version 4), which is also the default on many other distros.



Answered By - l0b0