我正在編寫一個腳本來根據位置更改一些設置,為此我選擇主機名稱作為基準。我的目標是,如果我的主機名稱條件成立,請執行此操作。為此,我正在編寫一個 shell 腳本,它比較 if 語句中的一些內容,我想列印成功的 if 條件,但沒有辦法做到這一點。這是我的腳本。
#!/bin/bash
location1=india
location2=eurpoe
location3=asia
location4=usa
location5=africa
location6=tokyo
echo "Checking Hostname"
hstname=`hostname | cut -f1 -d'-'`
echo "This is the $hstname"
#if [ $hstname == $location1 ] && [ $hstname == $location2 ] && [ $hstname == $location3 ] && [ $hstname == $location4 ] && [ $hstname == $location5 ] && [ $hstname == $location6 ] ;
if [[ ( $hstname == $location1 ) || ( $hstname == $location2 ) || ( $hstname == $location3 ) || ( $hstname == $location4 ) || ( $hstname == $location5 ) || ( $hstname == $location6 ) ]] ;
then
echo "This is part of " ;##Here i want to print true condition of above if statement##
else
echo "Please set Proper Hostname location wise." ;
fi
我無法找到列印 if 語句中為 true 的條件的方法。
答案1
將有效位置儲存在單一變數中並對其進行循環:
VALID_LOCATIONS="india europe asia usa africa tokyo"
hstname=`hostname | cut -f1 -d'-'`
for LOC in $VALID_LOCATIONS
do
if [[ $LOC == $hstname ]]; then
LOCATION=$LOC
fi
done
if [[ $LOCATION == "" ]]; then
echo "Please set Proper Hostname location wise."
else
echo "This is part of $LOCATION"
fi
結果:
This is part of europe
答案2
您可以使用
if [ $hstname == $location1 ] || [ $hstname == $location2 ] || [ $hstname == $location3 ] ; then
但不要忘記空格!
最好對條件中的所有位置使用“case”。