Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

bash

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 arguments error.

What am I doing wrong?

like image 953
JonaSc Avatar asked Jan 29 '14 07:01

JonaSc


2 Answers

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

like image 180
John1024 Avatar answered Oct 24 '22 09:10

John1024


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)
like image 39
Reinstate Monica Please Avatar answered Oct 24 '22 09:10

Reinstate Monica Please