exclamation mark to test variable is true or not in bash shell

前端 未结 3 1215
迷失自我
迷失自我 2021-01-14 05:20

I know in shell the exclamation mark can invert the outcome of condition. Here I wanna use it to test variable is true or false .

#! /bin/bash
bat=false
if [         


        
3条回答
  •  余生分开走
    2021-01-14 05:59

    if tests the results of commands and can't directly test the values of variables. In this case you're using it in conjunction with the test/[ command, which is an ordinary command and can be used anywhere.

    [ -f ./foo.txt ] && echo "foo.txt exists"
    

    or equivalently

    test -f ./foo.txt && echo "foo.txt exists"
    

    both test whether a file exists at the path ./foo.txt.

    Depending on what you mean by "true", you can use the test or [ shell builtin to determine whether a variable is equal to another, and for some other functions like testing whether a directory or file exists.

    You can use if [ -z "$variable" ]; then ...; fi to check whether a variable is the empty string.

    If you want to check whether the variable is set at all, even to an empty value, you can use parameter expansion [ -z "${var+x}" ]. It only evaluates to true (meaning has exit status zero) when var is undefined.

    If you want to compare a variable against a fixed string you can use [ "$var" = "some-string" ] or use case e.g.

    case "$var" in
       some-string)
         dostuff
       ;;
    esac
    

    Note that you can negate that the result of test/[ using !.

    if ! [ -z "$var" ]; then
        do-something
    fi
    

    Does negate the condition.

    However, ! is also valid as an argument to test/[

    if [ ! -z "$var" ]; then
        do-something
    fi
    

    means the same thing.

提交回复
热议问题