在bash中,如何检查字符串是否以某个值开头? [英] In bash, how can I check if a string begins with some value?

查看:413
本文介绍了在bash中,如何检查字符串是否以某个值开头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查一个字符串是否以node开头。 node001。类似

I would like to check if a string begins with "node" e.g. "node001". Something like

if [ $HOST == user* ]  
  then  
  echo yes  
fi

如何正确地做?

我还需要结合表达式来检查HOST是user1还是以node开头

I further need to combine expressions to check if HOST is either "user1" or begins with "node"

if [ [[ $HOST == user1 ]] -o [[ $HOST == node* ]] ];  
then  
echo yes 
fi

> > > -bash: [: too many arguments

如何正确地执行?

推荐答案

This snippet on the Advanced Bash Scripting Guide says:

# The == comparison operator behaves differently within a double-brackets
# test than within single brackets.

[[ $a == z* ]]   # True if $a starts with an "z" (wildcard matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).

所以你已经有了

So you had it nearly correct; you needed double brackets, not single brackets.

对于第二个问题,您需要可以这样写:

With regards to your second question, you can write it this way:

HOST=user1
if  [[ $HOST == user1 ]] || [[ $HOST == node* ]] ;
then
    echo yes1
fi

HOST=node001
if [[ $HOST == user1 ]] || [[ $HOST == node* ]] ;
then
    echo yes2
fi



Which will echo

yes1
yes2

Bash 如果语法难以用于(IMO)。

Bash's if syntax is hard to get used to (IMO).

这篇关于在bash中,如何检查字符串是否以某个值开头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆