Does not work to execute command in double brackets in bash

后端 未结 3 373
不知归路
不知归路 2021-01-21 12:41

In an attempt to stay consistent i have tried to use double brackets [[ ]] in all my if statements. I did however get into a problem when i was going to check the return value f

3条回答
  •  粉色の甜心
    2021-01-21 13:19

    If you're just checking the return value of the command, drop the double brackets.

    if $command
    then
        echo "Command succeeded"
    else
        echo "Command failed: $!"
    fi
    

    The double brackets are a test command. (Well, not really, but their a takeoff of the single square brackets that were an alias to the test command.) In early Bourne shell, you would see things like:

    if test -z "$string"
    then
        echo "This is an empty string"
    fi
    

    The square brackets were syntactic sugar:

    if [ -z "$string" ]
    then
        echo "This is an empty string"
    fi
    

    So, if you're not doing an actual test, you can eliminate the double or single square brackets.

    If you're using square brackets, you should use the double ones and not the single ones because the double ones are a bit more forgiving and can do a bit more:

    if [ -z $string ]    #  No quotes: This will actually fail if string is zero bytes!
    
    if [[ -z $string ]]  #  This will work despite the lack of quotes
    

提交回复
热议问题