Bash/sh - difference between && and ;

前端 未结 7 810
轮回少年
轮回少年 2020-12-07 11:22

I normally use ; to combine more than one command in a line, but some people prefer &&. Is there any difference? For example, cd ~; c

相关标签:
7条回答
  • 2020-12-07 11:56

    If previous command failed with ; the second one will run.

    But with && the second one will not run.

    This is a "lazy" logical "AND" operand between operations.

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

    In cmd1 && cmd2, cmd2 is only executed if cmd1 succeeds (returns 0).

    In cmd1 ; cmd2, cmd2 is executed in any case.

    Both constructs are part of a POSIX-compliant shell.

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

    && means to execute next command if the previous exited with status 0. For the opposite, use || i.e. to be executed if previous command exits with a status not equal to 0 ; executes always.

    Very useful when you need to take a particular action depending on if the previous command finished OK or not.

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

    && allows for conditional execution while ; always has the second command being executed.

    In e.g. command1 && command2, command2 will only execute when command1 has terminated with exit 0, signalling all went well, while in command1 ; command2 the second command will always be executed no matter what the result was of command1.

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

    && is logical AND in bash. Bash has short-circuit evaluation of logical AND. This idiom is a simpler way of expressing the following:

    
    cmd1;rc=$?
    if [ $rc -eq 0 ]; then
       cmd2
    fi
    

    Whereas the ; version is merely:

    
    cmd1
    cmd2
    
    0 讨论(0)
  • 2020-12-07 12:08

    I'm using && because a long time ago at the nearby computer:

    root# pwd
    /
    root# cd /tnp/test; rm -rf *
    cd: /tnp/test: No such file or directory
    ...
    ... and after a while ...
    ...   
    ^C
    

    but not helped... ;)

    cd /tnp/test && rm -rf * is safe... ;)

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