Does not work to execute command in double brackets in bash

后端 未结 3 345
不知归路
不知归路 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:29

    Double braces are a shortcut for test. In your examples, what's happening is that you're testing the shell variable $command for existence.

    if [[ $PWD ]]; then
        echo PWD is set to a value
    fi
    
    if [[ $NOT_A_REAL_VAR ]]; then
        echo Nope, its not set
    fi
    

    In your second example, you're using command substitution to check that command output something on standard output.

    if [[ $(echo hi) ]]; then
        echo "echo said hi'
    fi
    
    if [[ $(true) ]]; then #true is a program that just quits with successful exit status
        echo "This shouldn't execute"
    fi
    

    Your third example is the same as your first, pretty much. You use the curly braces if you want to group your variables. for example if you want to put an 's' after something.

    WORD=Bike
    echo "$WORDS" #won't work because "WORDS" isn't a variable
    echo "${WORD}S" # will output "BikeS"
    

    Then in your fifth example, you are running the program that is sitting inside command.

    So, if you want to test some strings, use [[ ]] or [ ]. If you just want to test the exit status of a program, then don't use those, just use a bare if.

    Check man test for details on the braces.

提交回复
热议问题