我如何在bash脚本中仅获得当前的工作目录名称,甚至更好,仅是终端命令。
pwd给出了当前工作目录的完整路径,例如/opt/local/bin但是我只想要bin
#1楼
以下命令将以bash脚本打印当前工作目录。
pushd .
CURRENT_DIR="`cd $1; pwd`"
popd
echo $CURRENT_DIR
#2楼
使用basename程序。 对于您的情况:
% basename "$PWD"
bin
#3楼
您可以结合使用pwd和basename。 例如
#!/bin/bash
CURRENT=`pwd`
BASENAME=`basename "$CURRENT"`
echo "$BASENAME"
exit;
#4楼
不需要基名,特别是不需要运行pwd的子shell(它增加了额外且昂贵的fork操作 ); Shell可以使用参数扩展在内部执行此操作:
result=${PWD##*/} # to assign to a variable
printf '%s\n' "${PWD##*/}" # to print to stdout
# ...more robust than echo for unusual names
# (consider a directory named -e or -n)
printf '%q\n' "${PWD##*/}" # to print to stdout, quoted for use as shell input
# ...useful to make hidden characters readable.
请注意,如果在其他情况下(不是PWD ,而是其他具有目录名的变量)应用此技术,则可能需要修剪任何斜杠。 下面使用bash的extglob支持来工作,即使有多个尾部斜杠也是如此:
dirname=/path/to/somewhere//
shopt -s extglob # enable +(...) glob syntax
result=${dirname%%+(/)} # trim however many trailing slashes exist
result=${result##*/} # remove everything before the last / that still remains
printf '%s\n' "$result"
或者,不使用extglob :
dirname="/path/to/somewhere//"
result="${dirname%"${dirname##*[!/]}"}" # extglob-free multi-trailing-/ trim
result="${result##*/}" # remove everything before the last /
#5楼
$ echo "${PWD##*/}"