8

Running

bash -c 'bash -c "echo test1; exit 1;" &> /tmp/x; buildresult=$?; tail -n 100 /tmp/x; exit $buildresult;'

results in test1 being printed to console and echo $? to print 1 which in my understanding is correct, because the command should return with what the inner [b/d]ash -c returned whereas

dash -c 'dash -c "echo test1; exit 1;" &> /tmp/x; buildresult=$?; tail -n 100 /tmp/x; exit $buildresult;'

results in the same output, but returns with 0 according to echo $?.

I'd like to understand this difference in order to broaden my understanding of shells and portable shell programming.

I'm using bash 4.4.12 and dash 0.5.8-2.3ubuntu1 on Ubuntu 17.10 (Artful Aardvark).

20

&> is not in POSIX and isn't supported by dash. It's parsed as & >, so the command is backgrounded instead. Backgrounded commands are given an exit status of zero from the perspective of the parent, since they haven't exited by the time you read $?.

That's also why (for me at least) the "test1" output appears in my prompt, after the command has finished.

Bash's &> foo is equivalent to > foo 2>&1, and a portable script should use the latter.

  • 5
    &> is in POSIX. That's & followed by >. In foo &> bar, that's foo & to start foo in background and > bar to perform a redirection without a command. bash is not POSIX compliant when it's interpreting it differently. – Stéphane Chazelas Nov 18 '17 at 21:54
  • 4
    Interesting enough is that this wasn't mentioned in wiki.ubuntu.com/DashAsBinSh I took a liberty to edit the page and include that – Sergiy Kolodyazhnyy Nov 18 '17 at 22:39

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.