linux - 在 bash 中获取目录或文件的基本名称的快速且正确的方法

标签 linux bash shell substitution basename

我有这个代码:

get_base() { echo "${1##*/}"; }

在我们有 1 个或更多之前,这可以正常工作 斜杠

我找到了解决方法,但是 问题是我们需要启用 extglob,而我不需要 想要那个:

ari@ari-gentoo ~ % x='/home/ari///'

ari@ari-gentoo ~ % echo "${x%%+(/)}"
/home/ari

然后我们可以 obv 将它保存到一个 tmp var 并运行 basename 替换它

无论如何,我的问题是,有没有合适的方法来做到这一点 而且它仍然很快(意味着没有调用外部命令 因为这个函数被调用了很多)没有 需要启用任何花哨的功能吗?

提前感谢您的回答:)

问答

no as all of those solutions either use commands or have a substitution expression that only strips the last slash, not multiples :) (e.g. /home/ari/// with expr ${x%/} would become only /home/ari// when it needs to be /home/ari)

  • “正确”是什么意思

By proper I mean 'achieved without enabling extglob or any other fancy features'

最佳答案

这是一种方法:

get_base() {
  set -- "${1%"${1##*[!/]}"}"
  printf '%s\n' "${1##*/}"
}
$ get_base /home/oguz//
oguz
$ get_base /root
root
$ get_base /

$ get_base .bash_history
.bash_history

关于linux - 在 bash 中获取目录或文件的基本名称的快速且正确的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74089893/

相关文章:

c - 在 C 中刷新 linux 串行缓冲区

linux - 如何在多个文件中运行多年和 12 个日历月的时间戳?

bash - 为什么 shell 命令没有按我预期的顺序执行?

python - 如何杀死正在运行的python进程?

linux - 为 0 或 4(不是 1、2、3)指定匹配重复

c - 在c程序中用sudo执行shell命令

linux - 如何仅将最新的子目录复制到目标 linux shell 脚本

c++ - Linux 中可以使用数据报管道吗?

linux - 如何在Eclipse中包含Linux内核开发的asm头目录?

bash - BASH 中可以根据另一个变量的内容调用变量吗?