0

I'm writing a script to change few setting according to location and to do this i selected hostname as a benchmark. My aim is, if my hostname condition comes true then do this. For this i'm writing a shell script which is comparing few thing in if statement, i want to print success if condition but not getting a way to do so. Here is my script.

#!/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

I'm not able to find a a way to print condition which got true in if statement.

alexander.polomodov
  • 1,060
  • 3
  • 10
  • 14
root
  • 39
  • 2
  • 8

2 Answers2

0

You can use

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

But do not forget the spaces !!

It should maybe better to use "case" with all the locations in the condition.

Dom
  • 6,628
  • 1
  • 19
  • 24
  • what will be the print or echo statement by which we will get where our if condition got match ? – root Sep 03 '18 at 06:43
0

Store the valid locations in a single variable and loop over it:

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

Result:

This is part of europe
Gerald Schneider
  • 19,757
  • 8
  • 52
  • 79