nathmorp
nathmorp

Reputation: 31

how to compare the name of computer with the list of names inside if-statement

-for bash script- i would like to know if it is possible to compare one computer name that was added with a list of computer names inside if[ $1 = ] without loop, just to check if it is computer from list - proceed, if not - stop. Thank u for your ideas

Upvotes: 2

Views: 214

Answers (3)

William
William

Reputation: 4935

There are a couple of ways. If you really want to use an if, you can do something like this (note the spaces around the variables):

#!/bin/bash
COMPUTERS="hosta hostb hostc"

if [[ " $COMPUTERS " =~ " $1 " ]] ; then
    echo "Yes, $1 is in the list"
else
    echo "No, $1 is not in the list"
fi

I'm fond of case myself:

case " $COMPUTERS " in
    *" $1 "*) echo "Yes, $1 is in the list" ;;
    *) echo "No, $1 is not in the list" ;;
esac

Note: These aren't foolproof. For example, "hosta hostb" will match which is probably not what you want, but if you know your data is well formed, or apply additional checks it's simple and works.

Upvotes: 1

uzsolt
uzsolt

Reputation: 6027

If you've a space-seperated list with available hostnames:

COMPUTERS="hosta hostb hostc"
echo ${COMPUTERS} | grep -qw "$1" && echo "$1 is in the list"

Upvotes: 0

Anew
Anew

Reputation: 5492

Not sure why you don't want to use a loop:

COMPUTERS=( hosta hostb hostc )

for COMPUTER in ${COMPUTERS[@]}; do
    if [ "${COMPUTER}" == "${1}" ];
    then
        echo "Yep. It's in the list."
    fi
done

Upvotes: 3

Related Questions