2017-06-27 103 views
0

我從檢索VMware Tools的主機名,並試圖評估如果兩個變量存在於我的腳本:檢查在bash腳本變量存在

selection=2 

# Check if hostname is present in guestinfo 
hostname="$(vmtoolsd --cmd "info-get guestinfo.startup.hostname")" 

if [[ "$selection" = 2 && ! -z ${hostname+x} ]] 
then 
    echo "Args present." 
else 
    echo "Args NOT present." 
fi 

不管主機名的值是否在VMX設置配置文件,if語句返回「存在的參數」。

我認爲這是因爲執行了vmtoolsd命令,意味着'hostname'變量不爲空。不確定如何解決。

出了什麼問題?

回答

0

首先,清理你的測試 - 不要使用! -z,當你有-n。

此外,如果您將x添加到主機名,它將始終爲真(它總是會自己返回x)。 Bash從不需要+ x,擺脫它。

if [[ "$selection" = 2 && -n $hostname ]]; then 
    echo "Args present." 
else 
    echo "Args NOT present." 
fi