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

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

问题描述

我想检查一个字符串是否以节点"开头,例如节点001".类似的东西

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

我该怎么做才能正确?

推荐答案

高级 Bash 脚本指南 说:

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

[[ $a == z* ]]   # True if $a starts with a "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

哪个会回声

yes1
yes2

Bash 的 if 语法很难习惯(IMO).

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

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

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