问题描述
我需要检查路径是否包含'*'字符作为最后一位数字.
I need to check if a path contains the '*' character as last digit.
我的方法:
length=${#filename}
((filename--))
#use substring to get the last character
if [ ${img:$length:1} == "*"] ;then
echo "yes"
fi
这将返回 [: too many arguments
错误.
This returns the [: too many arguments
error.
我在做什么错了?
推荐答案
[ "${filename:$length:1}" == "*" ] && echo yes
在您的帖子中,"*"
和]
之间没有空格.这使bash感到困惑.如果语句以[
开头,则bash坚持要求其最后一个参数为]
.没有空格,最后一个参数是"*"]
,在删除引号后,它变为*]
,而不是]
.
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 ]
.
将它们放在一起:
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
-1
是获取最后一个字符的简写.另一种可能性是:
The -1
is shorthand for getting the last character. Another possibility is:
[[ $filename = *\* ]] && echo yes
这使用了bash更强大的条件测试[[
.上面的代码查看$filename
是否与glob模式*\*
相匹配,其中第一个星号表示任何字符中的零个或多个",而后两个字符\*
表示字面上的星形字符.因此,以上测试文件名是否以文字*
结尾.使用[[
解决此问题的另一种方法可以在@broslow的答案中找到.
This uses bash's more powerful conditional test [[
. The above sees if $filename
is 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中最后一个字符串字符是否等于'*'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!