如何检查最后一个字符串字符是否等于 Bash 中的“*”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21425006/
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-18 09:23:56  来源:igfitidea点击:

How to check if the last string character equals '*' in Bash?

stringbash

提问by JonaSc

I need to check if a path contains the '*' character as last digit.

我需要检查路径是否包含“*”字符作为最后一位数字。

My approach:

我的做法:

length=${#filename}
((filename--))
#use substring to get the last character
if [ ${img:$length:1} == "*"] ;then
   echo "yes"
fi

This returns the [: too many argumentserror.

这将返回[: too many arguments错误。

What am I doing wrong?

我究竟做错了什么?

回答by John1024

[ "${filename:$length:1}" == "*" ] && echo yes

In your post, there was no space between "*"and ]. This confuses bash. If a statement begins with [, bash insists that its last argument be ]. Without the space, the last argument is "*"]which, after quote removal, becomes *]which is not ].

在您的帖子中,"*"和之间没有空格]。这会混淆 bash。如果语句以 开头[,bash 坚持其最后一个参数是]。如果没有空格,最后一个参数是"*"]which 在去除引号后变成*]which is not ]

Putting it all together:

把它们放在一起:

length=${#filename}
((length--))
[ "${filename:$length:1}" == "*" ] && echo yes

MORE:As per the comments below, the three lines above can be simplified to:

更多:根据下面的评论,上面的三行可以简化为:

[ "${filename: -1}" == "*" ] && echo yes

The -1is shorthand for getting the last character. Another possibility is:

-1是简写形式,得到的最后一个字符。另一种可能是:

[[ $filename = *\* ]] && echo yes

This uses bash's more powerful conditional test [[. The above sees if $filenameis matches the glob pattern *\*where the first star means "zero or more of any character" and the last two characters, \*, mean a literal star character. Thus, the above tests for whether filename ends with a literal *. Another solution to this problem using [[can be found in @broslow's answer.

这使用了 bash 更强大的条件测试[[。上面查看是否$filename与 glob 模式匹配,*\*其中第一个星号表示“零个或多个任何字符”,最后两个字符\*, 表示文字星号字符。因此,上述测试文件名是否以文字结尾*[[可以在@broslow 的回答中找到使用此问题的另一种解决方案。

回答by Reinstate Monica Please

Just use regex

只需使用正则表达式

if [[ "$filename" =~ '*'$ ]]; then 
  echo "yes"
fi

Couple of issues in your syntax.

您的语法中有几个问题。

  • You need a space before the last ]
  • Make sure to quote variables inside single brackets
  • ${variable:${#variable}:1}won't return any characters, ${variable:$((${#variable}-1))}should work (note though the 1 length at the end is redundant)
  • 在最后一个之前需要一个空格 ]
  • 确保在单括号内引用变量
  • ${variable:${#variable}:1}不会返回任何字符,${variable:$((${#variable}-1))}应该可以工作(请注意,尽管末尾的 1 长度是多余的)