Mild Fuzz
Mild Fuzz

Reputation: 30823

How can I check the last character in a string in bash?

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.

Upvotes: 6

Views: 11359

Answers (4)

crafter
crafter

Reputation: 6297

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

Upvotes: 0

user1019830
user1019830

Reputation:

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

Upvotes: 4

devnull
devnull

Reputation: 123708

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

Upvotes: 3

fedorqui
fedorqui

Reputation: 290525

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

Upvotes: 12

Related Questions