Bash:检查主机名是否为 vq* 如何使用通配符?
我有下一个代码,如果主机名与 v-qai01 或任何其他 vq* 服务器匹配,我需要它回显 1:
if [ `hostname -s` -eq `v-q*` ]; then
echo "1"
fi
我有几个错误:
./run.sh: line 3: v-q*: command not found
./run.sh: line 3: [: v-qai01: unary operator expected
请问有什么建议吗?
如果我有下一个案例怎么办?
hostname=`hostname -s`
portalesWildcard=v-*ws*
qaiservers={'v-qai01' 'v-qai02'}
portales={'t1wsyellar01' }
if [[ ${hostname} = ${qaiservers} ]]; then
echo "yes"
fi
谢谢
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:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用双方括号,
=
运算符将接受通配符:当您需要更高级的字符串匹配时,它还有一个
=~
运算符用于正则表达式匹配。这将检查主机名是否也以一位或多位数字结尾:Use double square brackets and the
=
operator will accept wildcards: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:您可以使用
case
语句:you can use the
case
statement:原始海报的实际问题是他们在字符串周围使用反引号:
而不是字符串引号。反引号告诉 shell 将其中的字符串作为命令执行。在这种情况下,shell 尝试执行:
但失败了。
The actual problem that the original poster had was that they used backticks around the string:
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:
which failed.
这将从字符串的开头删除
vq
。如果条件为真,则您的主机名与vq*
匹配This will remove
v-q
from the beginning of the string. If the condition is true, your hostname matchesv-q*