Difference in Bash between IF statements with parenthesis and square brackets

后端 未结 2 636
长情又很酷
长情又很酷 2020-12-12 11:11

While learning a bit about bash, I come to see four types of ways of working with if statements:

  • Single Parenthesis - ( ... )
  • Double Pare
2条回答
  •  一生所求
    2020-12-12 12:14

    The tests you had listed :

    • Single Parenthesis - ( ... ) is creating a subshell
    • Double Parenthesis - (( ... )) is for arithmetic operation
    • Single Square Bracket - [ ... ] is the syntax for the POSIX test
    • Double Square Brackets - [[ ... ]] is the syntax for bash conditional expressions (similar to test but more powerful)

    are not exhaustive, you can use boolean logic

    if command; then ...
    

    too, because the commands have exit status. In bash, 0 is true and > 0 is false.

    You can see the exit status like this :

    command
    echo $?
    

    See :

    http://wiki.bash-hackers.org/syntax/basicgrammar
    http://wiki.bash-hackers.org/syntax/arith_expr
    http://mywiki.wooledge.org/BashGuide/TestsAndConditionals

提交回复
热议问题