Bash: how to check if the last character of a string is '*'

I need to check if the path contains the character '*' as the 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 error "[: too many arguments".

What am I doing wrong?

+4
source share
2 answers
[ "${filename:$length:1}" == "*" ] && echo yes

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

Putting it all together:

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

: :

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

-1 . :

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

bash [[. , $filename glob *\*, " ", \* . , , *. [[ @broslow.

+11

regex

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

.

  • ]
  • .
  • ${variable:${#variable}:1} - , ${variable:$((${#variable}-1))} ( , 1 )
+3

Source: https://habr.com/ru/post/1524232/


All Articles