1

Whats the best way to achieve the following?

I want my script to find out which postion the host its running on is in a list of hosts.

thisHost=$(hostname)

machineList="pc02 server03 host01 server05"

So if thisHost=host01 I would get back postion 3.

The machine list would never be contain more than 10 items.

I could do a comparison match in a for loop but would like to know if there is a better way ?

4 Answers 4

4

If you need to check many hosts, you can prepare a better structure for faster lookup: an associative array:

#! /bin/bash
machineList='pc02 server03 host01 server05'
declare -A machine_number
i=1
for machine in $machineList ; do
    machine_number[$machine]=$((i++))
done

thisHost=host01
echo ${machine_number[$thisHost]}

You can also use external tools:

read n _rest < <(echo "$machineList"
                 | tr ' ' '\n'
                 | nl
                 | grep -Fw "$thisHost")
echo $n
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I edited the question to say the list would only be a 10 or so machines
1

Bash solution:

thisHost="host01"
machineList="pc02 server03 host01 server05"
machineListArr=($machineList)

for i in "${!machineListArr[@]}"; do 
    [ "$thisHost" = "${machineListArr[$i]}" ] && echo "position: $((i+1))"
done

The output:

position: 3

Comments

1

Awk one-line solution:

thisHost="host01"
machineList="pc02 server03 host01 server05"

awk -v RS=" " -v h="$thisHost" '$0==h{ print NR }' <<<"$machineList"

The output:

3

Comments

1

(1) An inexpensive one-liner:

    host='host01'
    machineList="pc02 server03 host01 server05"

    wc -w <<< ${machineList/%${host}*/dummy}

Substitute the rest of the list beginning with $host with dummy and count the words with wc.

(2) Pure Bash:

    host='host01'
    machineList="pc02 server03 host01 server05"

    shortList=( ${machineList/%${host}*/dummy} )
    echo  ${#shortList[@]}

Shorten the list as shown above and return the number of elements of the array shortList.

The output is 3 in both solutions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.