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.

  • That's because there is no way to get which part of the condition was false. You will have to do an if ... else clause for every single location. – Gerald Schneider Sep 3 '18 at 6:27
  • why not use case instead of if? – Dennis Nolte Sep 3 '18 at 7:28
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
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.

  • what will be the print or echo statement by which we will get where our if condition got match ? – root Sep 3 '18 at 6:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.