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

后端 未结 2 1727
暗喜
暗喜 2020-12-31 07:22

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

My approach:

length=${#filename}
((file         


        
2条回答
  •  悲哀的现实
    2020-12-31 08:11

    [ "${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 ].

    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 -1 is shorthand for getting the last character. Another possibility is:

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

    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.

提交回复
热议问题