Bash Shell:了解是否设置了变量

时间:2020-01-09 10:42:16  来源:igfitidea点击:

如何检查BSD/Apple OS X/Unix/Linux之类的操作系统中是否定义了名为$input的bash shell变量?

方法1:Bash变量存在检查

确定是否定义了$input的语法如下:

${Variable?Error $Variable is not defined}

或者

${Variable:?Error $Variable is not defined}

在此示例中,如果未定义变量$input,则脚本将停止执行:

input="Foo bar"
echo ${input?Error $input is not defined.}
unset input
echo ${input?Error $input is not defined.}

输出示例:

Foo bar
bash: input: Error $input is not defined.

在此示例中,确保$input已定义并且不为空,执行:

[[  $input && ${input-x} ]] 
input="Foo" 
[[  $input && ${input-x} ]] && echo "Found" || echo "Not found"
unset input
[[  $input && ${input-x} ]] && echo "Found" || echo "Not found"

这是确保已定义$_php_map_extension的示例:

# read config data
        loadConfigData "${_t_domain_php_conf}" $LINENO "${FUNCNAME[0]}"
 
	# make sure it is defined and not empty 
	if [[ $_php_map_extension && ${_php_map_extension-_} ]]
        then
                at=${#_php_map_extension[*]}                                            # get total elements in an array
                s=""
                echo '## Map extension to .php? ##' 
                echo 'fastcgi.map-extensions = ('  
                for (( i=0; i<${at}; i++ ));
                do
                        [ $i -lt $(( $at - 1 )) ] && s="," || s=""                      # remove , for last item in an array                    
                        echo "      \".${_php_map_extension[i]}\" -  \".php\"${s}" 
                done
                echo ')'
	else 
		echo "Skiping php map extension as $_php_map_extension is not defined in /usr/local/etc/theitroad/conf/php.conf."
        fi

输出示例:

Skiping php map extension as $_php_map_extension is not defined in /usr/local/etc/theitroad/conf/php.conf

或者

## Map extension to .php? ##
fastcgi.map-extensions = (
      ".html" -  ".php",
      ".htm" -  ".php",
      ".phtml" -  ".php",
      ".php3" -  ".php",
      ".php4" -  ".php"
)

方法#2:isvarset()函数

上面的示例对于完整性检查很有用。
最后,您可以使用以下代码:

isvarset(){
local v=""
[[ ! ${!v} && ${!v-unset} ]] && echo "Variable not found." || echo "Variable found."
}
 
# find out if $vech defined or not
vech="Bus" && isvarset vech
vech="" && isvarset vech
unset vech && isvarset vech

方法3:使用STRING的长度

测试命令的-z选项返回STRING的长度为零的TRUE。
您可以使用以下语法:

### set or not???
input="Foo"
[ -z "${input+x}" ] && echo "$input is not set" || echo "$input found and is set to \"$input\"."
 
### Not set at ALL
unset input
[ -z "${input+x}" ] && echo "$input is not set" || echo "$input found and is set to \"$input\"."
 
### 'set but empty' or not?
input=""
[ -z "$input" -a "${input+x}" = "x" ] && echo "$input variable is set with empty value." || echo "$input found and is set to "$input\""

上面的语法将告诉您在bash shell脚本中是否定义了变量或者未定义变量或者定义为空值。