mvdan / sh

A shell parser, formatter, and interpreter with bash support; includes shfmt
https://pkg.go.dev/mvdan.cc/sh/v3
BSD 3-Clause "New" or "Revised" License
6.98k stars 332 forks source link

shfmt bug: `&>` is broken onto a new line, while `>&` isn't #991

Closed tandy-1000 closed 1 year ago

tandy-1000 commented 1 year ago

When shfmt sees a &>, it is broken onto a new line:

{ echo "foo" } &>/dev/null || {
    echo "bar"
}

Becomes:

{ echo "foo" } &
    >/dev/null || {
    echo "bar"
}

The transformation also breaks the code.

If you switch &> with >& this does not happen.

mvdan commented 1 year ago

What did you run exactly?. It's likely that you're trying to use POSIX mode when &> is bash syntax. Unfortunately, &> is also valid POSIX syntax; it just parses as & >, i.e. "background command then start a redirection".

netrixken commented 1 year ago

Just noticed today

if ping -c 1 $default_gateway_ip &>/dev/null; then

becomes

    if
        ping -c 1 $default_gateway_ip &
        >/dev/null
    then

Using https://marketplace.visualstudio.com/items?itemName=mkhl.shfmt

mvdan commented 1 year ago

The "fix" above is to give a helpful error, since I suspect that both of you were using POSIX mode to try to parse Bash syntax. You should be using the Bash mode, which should kick in automatically if your shell script has a .bash extension or a shebang like #!/usr/bin/bash. More details in the commit above.