How to tell if a string is not defined in a Bash shell script

后端 未结 12 2163
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 04:42

If I want to check for the null string I would do

[ -z $mystr ]

but what if I want to check whether the variable has been defined at all? O

12条回答
  •  借酒劲吻你
    2020-12-02 04:55

    The Bash Reference Manual is an authoritative source of information about bash.

    Here's an example of testing a variable to see if it exists:

    if [ -z "$PS1" ]; then
            echo This shell is not interactive
    else
            echo This shell is interactive
    fi
    

    (From section 6.3.2.)

    Note that the whitespace after the open [ and before the ] is not optional.


    Tips for Vim users

    I had a script that had several declarations as follows:

    export VARIABLE_NAME="$SOME_OTHER_VARIABLE/path-part"
    

    But I wanted them to defer to any existing values. So I re-wrote them to look like this:

    if [ -z "$VARIABLE_NAME" ]; then
            export VARIABLE_NAME="$SOME_OTHER_VARIABLE/path-part"
    fi
    

    I was able to automate this in vim using a quick regex:

    s/\vexport ([A-Z_]+)\=("[^"]+")\n/if [ -z "$\1" ]; then\r  export \1=\2\rfi\r/gc
    

    This can be applied by selecting the relevant lines visually, then typing :. The command bar pre-populates with :'<,'>. Paste the above command and hit enter.


    Tested on this version of Vim:

    VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Aug 22 2015 15:38:58)
    Compiled by root@apple.com
    

    Windows users may want different line endings.

提交回复
热议问题