我如何在bash脚本中检索当前工作目录/文件夹名称,或者更好的是,仅仅是一个终端命令。
pwd给出了当前工作目录的完整路径,例如/opt/local/bin,但我只想要bin。
我如何在bash脚本中检索当前工作目录/文件夹名称,或者更好的是,仅仅是一个终端命令。
pwd给出了当前工作目录的完整路径,例如/opt/local/bin,但我只想要bin。
当前回答
令人惊讶的是,没有人提到这个只使用内置bash命令的替代方案:
i="$IFS";IFS='/';set -f;p=($PWD);set +f;IFS="$i";echo "${p[-1]}"
作为额外的奖励,你可以很容易地获得父目录的名称:
[ "${#p[@]}" -gt 1 ] && echo "${p[-2]}"
这些将在Bash 4.3 alpha或更新版本上工作。
其他回答
有很多方法可以做到这一点,我特别喜欢Charles的方法,因为它避免了一个新的过程,但在知道这一点之前,我用awk解决了它
pwd | awk -F/ '{print $NF}'
我通常在sh脚本中使用它
SCRIPTSRC=`readlink -f "$0" || echo "$0"`
RUN_PATH=`dirname "${SCRIPTSRC}" || echo .`
echo "Running from ${RUN_PATH}"
...
cd ${RUN_PATH}/subfolder
你可以用它来自动化事情……
下面grep with regex也可以,
>pwd | grep -o "\w*-*$"
不需要basename,特别是不需要运行pwd的子shell(这会增加额外且昂贵的fork操作);shell可以在内部使用参数展开:
result=${PWD##*/} # to assign to a variable
result=${result:-/} # to correct for the case where PWD=/
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
result=${result:-/} # correct for dirname=/ case
printf '%s\n' "$result"
或者,不使用extglob:
dirname="/path/to/somewhere//"
result="${dirname%"${dirname##*[!/]}"}" # extglob-free multi-trailing-/ trim
result="${result##*/}" # remove everything before the last /
result=${result:-/} # correct for dirname=/ case
您可以使用pwd和basename的组合。如。
#!/bin/bash
CURRENT=`pwd`
BASENAME=`basename "$CURRENT"`
echo "$BASENAME"
exit;