Unix

如果shell腳本中的條件為真,如何列印

  • September 3, 2018

我正在編寫一個腳本來根據位置更改一些設置,為此我選擇了主機名作為基準。我的目標是,如果我的主機名條件成真,那麼就這樣做。為此,我正在編寫一個 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 語句中為真的條件。

將有效位置儲存在單個變數中並對其進行循環:

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

您可以使用

if [ $hstname == $location1 ] || [ $hstname == $location2 ] || [ $hstname == $location3 ] ; then

但不要忘記空格!

最好對條件中的所有位置使用“案例”。

引用自:https://serverfault.com/questions/929145