I have wrote the following lines to obtain the last character of a string:
1 2 3 | str=$1 i=$((${#str}-1)) echo ${str:$i:1} |
It works for “abcd/”:
1 2 | $ bash last_ch.sh abcd/ / |
It does not work for “abcd*”:
1 2 | $ bash last_ch.sh abcd* array.sh assign.sh date.sh dict.sh full_path.sh |
It lists the files in the current folder.
That’s one of the reasons why you need to quote your variables:
1 | echo "${str:$i:1}" |
Otherwise, bash expands the variable & in this case does globbing before printing out. It is moreover better to quote the parameter to the script (in case you have a matching filename):
1 | sh lash_ch.sh 'abcde*' |
Also see the order of expansions in the bash reference manual. Variables are expanded before the filename expansion.