bash 相当于tcsh修饰符,用于提取路径组件

bash equivalent to tcsh modifiers for extracting path components

在 tcsh 中,我可以通过以下方式从路径末尾提取第二个路径元素

cd /some/long/directory/structure/path/
set x=`pwd`
echo ${x:h:h:t}
directory

如何在 bash 中执行相同的操作?

我是说,bash也有这种修饰符吗?

cd /some/long/path/somewhere
x=$PWD
basename "$(dirname "$x")"
>  path

dirname 获取参数父文件夹的绝对路径。 basename 获取参数的名称。

编辑:记得比我以前做的好多了。

csh 风格的修饰符可以与历史扩展一起使用(毫不奇怪,因为历史扩展是从 csh 借来的)。

$ cd /some/long/directory/structure/path/
$ echo !!:1:h:h:t
echo directory
directory

!!:1 选择前一个命令的字 1(从零开始计数),因此 cd.

的参数

echo directory 出现在标准错误上,因为 shell 默认在实际执行结果命令之前显示历史扩展的结果。)

在非交互式 bash 脚本中,@chepner 的回答中的历史扩展命令通常不可用。但是,您确实有参数扩展,例如:

$ cd /some/long//directory///structure/path/
$ set x=$(pwd)
$ echo $x
/some/long/directory/structure/path
$ y=${y%/*/*}      # each /* is equivalent to one :h
$ y=${y##*/}       # equivalent to :t
$ echo $y
directory