Search code examples
shellscriptingfish

is "&&" exactly equivalent to "and" in fish shell?


In fish shell, && and and seem to behave the same way. Are they exactly the same? And are there any edge cases in which they would behave differently?


Solution

  • While they're used for the same thing, they are fundamentally quite different:

    sh && is a binary operator that takes two commands, runs the first, and only if it succeeds, runs the second. The exit status is that of the first command if it fails, or the second command if it doesn't.

    fish and is a unary operator that takes a single command, and runs it if $status is 0. The exit status is optionally modified by the command if run.

    Here you can see the difference in arity:

    $ fish -c 'and echo true'
    true
    
    $ sh -c '&& echo true'
    sh: 1: Syntax error: "&&" unexpected
    

    Here you can see how and may operate on a command that's not immediately before it:

    $ fish -c 'false; set x 1; and echo true'
    (no output)
    
    $ sh -c 'false; x=1 && echo true'
    true