如何得到一个shell字符串的最后一个字符? [英] How to get the last character of a string in a shell?

查看:248
本文介绍了如何得到一个shell字符串的最后一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面的线得到一个字符串的最后一个字符:

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

str=$1
i=$((${#str}-1))
echo ${str:$i:1}

它适用于 ABCD /

$ bash last_ch.sh abcd/
/

它的不为 ABCD *工作

It does not work for abcd*:

$ bash last_ch.sh abcd*
array.sh assign.sh date.sh dict.sh full_path.sh last_ch.sh

它的列出了当前文件夹中的文件。

推荐答案

这就是为什么你需要引用您的变量的原因之一:

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

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

否则,bash扩展变量并且在这种情况下,打印出之前没有通配符。这也是最好的参数引用到脚本(如果你有一个匹配的文件名):

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 lash_ch.sh 'abcde*'

另请参阅 bash的参考手册扩展的顺序。变量文件名扩展之前被扩展。

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

这篇关于如何得到一个shell字符串的最后一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆