我想检查一个字符串是否以“node”开头,例如“node001”。就像是
if [ $HOST == user* ] then echo yes fi
我怎样才能正确地做到这一点?
我还需要结合表达式来检查 HOST 是“user1”还是以“node”开头
if [ [[ $HOST == user1 ]] -o [[ $HOST == node* ]] ]; then echo yes fi > > > -bash: [: too many arguments
Advanced Bash Scripting Guide上的这个片段说:
# 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).
所以你 几乎 是正确的;你需要 双 括号,而不是单括号。
关于你的第二个问题,你可以这样写:
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)。
if