What is the difference between double-ampersand (&&) and semicolon (;) in Linux Bash?

前端 未结 3 1817
盖世英雄少女心
盖世英雄少女心 2020-12-07 10:03

What is the difference between ampersand and semicolon in Linux Bash?

For example,

$ command1 && command2

vs



        
相关标签:
3条回答
  • 2020-12-07 11:01

    The && operator is a boolean AND operator: if the left side returns a non-zero exit status, the operator returns that status and does not evaluate the right side (it short-circuits), otherwise it evaluates the right side and returns its exit status. This is commonly used to make sure that command2 is only run if command1 ran successfully.

    The ; token just separates commands, so it will run the second command regardless of whether or not the first one succeeds.

    0 讨论(0)
  • 2020-12-07 11:06

    command1 && command2

    command1 && command2 executes command2 if (and only if) command1 execution ends up successfully. In Unix jargon, that means exit code / return code equal to zero.

    command1; command2

    command1; command2 executes command2 after executing command1, sequentially. It does not matter whether the commands were successful or not.

    0 讨论(0)
  • 2020-12-07 11:07

    The former is a simple logic AND using short circuit evaluation, the latter simply delimits two commands.

    What happens in real is that when the first program returns a nonzero exit code, the whole AND is evaluated to FALSE and the second command won't be executed. The later simply executes them both in order.

    0 讨论(0)
提交回复
热议问题