I need to ensure that the last character in a string is a /

x="test.com/"

if [[ $x =~ //$/ ]] ; then
        x=$x"extention"
else
        x=$x"/extention"
fi

at the moment, false always fires.

share|improve this question
up vote 8 down vote accepted

Like this, for example:

$ x="test.com/"
$ [[ "$x" == */ ]] && echo "yes"
yes

$ x="test.com"
$ [[ "$x" == */ ]] && echo "yes"
$ 

$ x="test.c/om"
$ [[ "$x" == */ ]] && echo "yes"
$ 

$ x="test.c/om/"
$ [[ "$x" == */ ]] && echo "yes"
yes

$ x="test.c//om/"
$ [[ "$x" == */ ]] && echo "yes"
yes
share|improve this answer
    
Awesome. What does the star denote? Will this get a false positive if x has multiple /? – Mild Fuzz Oct 9 '13 at 12:30
    
@MildFuzz the asterisk * denotes "any character". So you can also do [[ "$x" == *m/ ]] && echo "yes" that will say yes in this case, but not in x="test.comp/", for example. For multiple /` it will be also fine, check my updated examples. – fedorqui Oct 9 '13 at 12:33

Your condition was slightly incorrect. When using =~, the rhs is considered a pattern, so you'd say pattern and not /pattern/.

You'd have got expected results if you said

if [[ $x =~ /$ ]] ; then

instead of

if [[ $x =~ //$/ ]] ; then
share|improve this answer

You can index strings in Bash using ${var:index} and ${#var} to get the length of the string. Negative indices means the moving from the end to the start of the string so that -1 is index of the last character:

if [[ "${x:${#x}-1}" == "/" ]]; then
    # last character of x is /
fi
share|improve this answer
    
Negative indices are allowed, but you need a space to distinguish substring expansion from default value expansion: ${x: -1}. You aren't actually using a negative index, but a computed positive index. – chepner Oct 9 '13 at 12:58

You can do this generically using bash substrings $(string:offset:length} - length is optional

#x is the length of x

Therefore

$n = 1       # 1 character
last_char = ${x:${#x} - $n}

For future references,

$ man bash

has all the magic

${parameter:offset:length}

Substring Expansion. Expands to up to length characters of parameter starting at the character specified by offset. If length is omitted, expands to the substring of parameter starting at the character specified by offset. length and offset are arithmetic expressions ...

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.