简体   繁体   English

如何将计算机名称与if语句中的名称列表进行比较

[英]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. -对于bash脚本-我想知道是否可以将添加的一台计算机名称与if [$ 1 =]内无循环的计算机名称列表进行比较,只是检查它是否为列表中的计算机-继续,如果不-停下来。 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): 如果您确实要使用if,则可以执行以下操作(注意变量周围的空格):

#!/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. 例如,“ hosta hostb”将匹配您可能不需要的匹配项,但是如果您知道数据格式正确,或者应用其他检查,则很简单并且可以正常工作。

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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