Bash:检查主机名是否为 vq* 如何使用通配符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5955031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:30:03  来源:igfitidea点击:

Bash: check if hostname is v-q* how to use wildcards?

bashscriptingprogramming-languages

提问by BoDiE2003

I have the next code and I need it to echo 1 if the hostname matches with v-qai01 or any other v-q* servers:

我有下一个代码,如果主机名与 v-qai01 或任何其他 vq* 服务器匹配,我需要它来回显 1:

if [ `hostname -s` -eq `v-q*` ]; then
        echo "1"
fi

Im having several errors:

我有几个错误:

./run.sh: line 3: v-q*: command not found
./run.sh: line 3: [: v-qai01: unary operator expected

Any suggestions please?

请问有什么建议吗?

What if I have the next case?

如果我有下一个案例怎么办?

hostname=`hostname -s`

portalesWildcard=v-*ws*
qaiservers={'v-qai01' 'v-qai02'}
portales={'t1wsyellar01' }


if [[ ${hostname} = ${qaiservers} ]]; then
    echo "yes"
fi

Thanks

谢谢

回答by John Kugelman

Use double square brackets and the =operator will accept wildcards:

使用双方括号,=运算符将接受通配符:

#!/bin/bash

if [[ $(hostname -s) = v-q* ]]; then
    ...
fi

It also has a =~operator for regex matches when you need more advanced string matching. This would check that the host name also ends with one or more digits:

=~当您需要更高级的字符串匹配时,它还具有用于正则表达式匹配的运算符。这将检查主机名是否也以一位或多位数字结尾:

#!/bin/bash

if [[ $(hostname -s) =~ ^v-q.*[0-9]+$ ]]; then
    ...
fi

回答by glenn Hymanman

you can use the casestatement:

您可以使用以下case语句:

case $(hostname -s) in
  v-q*) echo yes ;;
  *) echo no ;;
esac

回答by Ms CodeGuru

The actual problem that the original poster had was that they used backticks around the string:

原始海报的实际问题是他们在字符串周围使用了反引号:

if [ `hostname -s` -eq `v-q*` ]; then

rather than string quotes. Backticks tell the shell to execute the string within them as a command. In this case, the shell tried to execute:

而不是字符串引号。反引号告诉 shell 将其中的字符串作为命令执行。在这种情况下,shell 尝试执行:

v-q* 

which failed.

哪个失败了。

回答by Bryan Drewery

This will remove v-qfrom the beginning of the string. If the condition is true, your hostname matches v-q*

这将从v-q字符串的开头删除。如果条件为真,则您的主机名匹配v-q*

hostname=`hostname -s`
if ! [ "${hostname#v-q}" = "${hostname}" ]; then
  echo "1"
fi