繁体   English   中英

我如何确切地确定变量是否未使用bash在文件中定义

[英]How i exactly determine if variable not defined in file using bash

以下文本文件包含ip_address变量。 档案如下

$ cat file
ip_address=10.78.1.0
filename=test.bin

现在具有bash脚本,用于检查ip_address定义(或是否可用)

#!/bin/bash

for list in $(cat file)
do
    eval $list
done

${ip_Address:?Error \$IP_Address is not defined}

[ -z ${ip_Address:-""} ] && printf "No IPaddress\n" || echo "$ip_Address"

现在,如果我的文件中不包含ip_address变量行,则脚本在此处中断,但如果存在,则再次检查ip_adress包含不包含任何值。

但是我不想破坏我的脚本,如果变量不可用,我想做点什么

喜欢

#!/bin/bash

for list in $(cat file)
do
    eval $list
done

if [ variable not available ]
then
    #do something
else
    #check variable set or not
    [ -z ${ip_Address:-""} ] && printf "No IP address\n" || echo "$ip_Address"
fi

尝试使用-z标志(实际上此标志检查变量是否为空,但不检查变量的可用性),如下所示

if [ -z  $ip_Address ]
then
    #do something
else 
    #rest of code
fi

但是在以下情况下失败

情况1:如果我的文件如下

$ cat file
  filename=test.bin

那么它必须进入if..块,并且可以。所以这不是问题

情况2:

如果我的文件如下

$ cat file
  ip_address=
  filename=test.bin

那么它必须进入else..块,但不是。 所以有问题

那么如何区分bash中定义的变量或可用的变量呢?

您可以使用${var-value}替换来区分未设置,设置但为空和非空。

case ${ip_address-UNSET} in UNSET) echo "It's unset." ;; esac
case ${ip_address:-EMPTY} in EMPTY) echo "It's set, but empty." ;; esac
case ${ip_address:+SET} in SET) echo "It's set and nonempty." ;; esac

这只是为了演示; 您的逻辑看起来可能会大不相同。

另请参见http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html

如果您正在使用bash 4.2(最新版本,尽管4.3应该很快发布……),则可以使用-v条件运算符来测试是否设置了变量。

if [[ -v ip_Address ]]; then
    printf "ip_Address is set\n";
fi

请注意, -v的参数是您要测试的变量的名称 ,因此您不必在其前面加上$

使用test的-n标志而不是-z

这将测试变量是否具有内容,还将识别变量是否未设置。

if [ -n "$ip_Address" ]
then
    # ip_address is set 
else 
    # ip_address is no content OR is not set
fi

对我来说,以下几行可以完成这项工作:

#!/bin/bash

if test $# -ne 1;
then
    echo "Usage: check_for_ip.sh infile"
    exit
fi

. $1

test -z "${ip_address}" && echo "No IP address" || echo "IP address is: ${ip_address}"

测试文件:

$ cat file1 
ip_address=
filename=test.bin
$ cat file2 
ip_address=10.78.1.0
filename=test.bin
$ cat file3
filename=test.bin

检测结果:

$ bash check_for_ip.sh file1
No IP address
$ bash check_for_ip.sh file2
IP address is: 10.78.1.0
$ bash check_for_ip.sh file3
No IP address

我不确定我是否理解了这个问题,因为这看起来很像您的解决方案; 也许您只是在测试中遗漏了“”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM