metaphy metaphy - 2 years ago 165
Bash Question

shell get the last character of a string

I have written the following lines to get the last character of a string:

echo ${str:$i:1}

It works for "abcd/":

$ bash abcd/

It does not work for "abcd*":

$ bash abcd*

It lists the files in the current folder.

Answer Source

That's one of the reasons why you need to quote your variables:

echo "${str:$i:1}"

Otherwise, bash expands the variable and in this case does globbing before printing out. It is also better to quote the parameter to the script (in case you have a matching filename):

sh 'abcde*'

Also see the order of expansions in the bash reference manual. Variables are expanded before the filename expansion.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download