简体   繁体   中英

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

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

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM