1

I have a file IP file which has:

$cat serverList
server 1 = 192.168.1.1
server 2 = 192.168.1.2
server 3 = 192.168.1.3
server 4 = 192.168.1.4
server 5 = 192.168.1.5

My Bash Code:

serverList="/home/user1/nic-test/server-list"

for i in $(cat $serverList | awk '{print $3}'); do

  s1=`ssh user1@$i /etc/sysconfig/ha/getactive.sh`

  if [[ $s1 == "NodeType: Active" ]]
  then
    activenode=$i
    standbynode=$server2
    node1=$server3
    node2=$server4
    node3=$server5
  fi
done

My Logic:

  • ssh to all the server IPs in the list and find out Active Node. If any node from the list will be active then assign that IP to the variable "activenode"

What I'm unable to do is : Once active node IP is assigned to variable activenode, I want other IPs from that file serverList to be assigned automatically to other variables (in any order):

standbynode=$server2
node1=$server3
node2=$server4
node3=$server5
3

First, awk can read files, no need for cat

Second, the 3rd field is the equal sign, use $NF for the last field

Third, and most important, using an array will make this so much easier:

mapfile -t servers < <(awk '{print $NF}' serverlist)
declare -p servers

outputs

declare -a servers=([0]="192.168.1.1" [1]="192.168.1.2" [2]="192.168.1.3" [3]="192.168.1.4" [4]="192.168.1.5")

Then, to accomplish your goal, I would do:

#!/usr/bin/env bash

mapfile -t servers < <(awk '{print $NF}' serverlist)

for idx in "${!servers[@]}"; do

  server=${servers[idx]}
  s1=$(ssh user1@"$server" /etc/sysconfig/ha/getactive.sh) 

  if [[ $s1 == "NodeType: Active" ]]; then
    activenode=$server
    ((standbyIdx = (idx + 1) % ${#servers[@]}))
    standbynode=${servers[standbyIdx]}

    unset 'servers[idx]' 'servers[standbyIdx]'
    othernodes=( "${servers[@]}" )
    break
  fi
done

if [[ -z $activenode ]]; then
    echo "No active nodes!"
    exit 1
fi

declare -p activenode standbynode othernodes

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.