我正在编写一个脚本,根据位置更改一些设置,为此我选择了主机名作为基准。我的目标是,如果我的主机名条件成立,则执行此操作。为此,我正在编写一个 shell 脚本,该脚本在 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 语句中成立的条件。
答案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”用于条件中的所有位置。