sub123
sub123

Reputation: 93

Shell / Korn script - set variable depending on hostname in list

I need to write a korn script that depending on the host the script is running on, will set a deployment directory (so say 5 hosts deploy the software to directory one and five other hosts deploy to directory two).

How could I do this - I wanted to avoid an if condition for every host like below

IF [hostname = host1] then $INSTALL_DIR=Dir1
ELSE IF [hostname = host2] then $INSTALL_DIR=Dir1

and would prefer to have a list of say Directory1Hosts and Directory2Hosts which contains all the hosts valid for each directory, and then I would just check if the host the script is running on is in my Directory1Hosts or Directory2Hosts (so only two IF conditions instead of 10).

Thanks for your help - have been struggling to find how to do effectively a contains clause.

Upvotes: 0

Views: 169

Answers (2)

Walter A
Walter A

Reputation: 20022

When you want to have configuration and code apart, you can make a config directory: one file with hosts for each install dir.

# cat installdirs/Dir1
host1
host2

With these files your code can be

INSTALL_DIR=$(grep -Flx "${hostname}" installdirs/* | cut -d"/" -f2)

Upvotes: 0

chepner
chepner

Reputation: 531625

Use a case statement:

case $hostname in
   host1) INSTALL_DIR=DIR1 ;;
   host2) INSTALL_DIR=DIR2 ;;
esac

or use an associative array

install_dirs=([host1]=DIR1 [host2]=DIR2)

...

INSTALL_DIR=${install_dirs[$hostname]}

Upvotes: 1

Related Questions