在 Bash 脚本中获取当前目录名称(没有完整路径)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1371261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:28:54  来源:igfitidea点击:

Get current directory name (without full path) in a Bash script

bashshell

提问by Derek Dahmer

How would I get just the current working directory name in a bash script, or even better, just a terminal command.

我将如何在 bash 脚本中仅获取当前工作目录名称,或者甚至更好,仅获取终端命令。

pwdgives the full path of the current working directory, e.g. /opt/local/binbut I only want bin

pwd给出当前工作目录的完整路径,例如/opt/local/bin但我只想要bin

回答by Charles Duffy

No need for basename, and especially no need for a subshell running pwd (which adds an extra, and expensive, fork operation); the shell can do this internally using parameter expansion:

不需要 basename,尤其不需要运行 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.


Note that if you're applying this technique in other circumstances (not PWD, but some other variable holding a directory name), you might need to trim any trailing slashes. The below uses bash's extglob supportto work even with multiple trailing slashes:

请注意,如果您在其他情况下应用此技术(不是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"

Alternatively, without extglob:

或者,没有extglob

dirname="/path/to/somewhere//"
result="${dirname%"${dirname##*[!/]}"}" # extglob-free multi-trailing-/ trim
result="${result##*/}"                  # remove everything before the last /

回答by Arkady

Use the basenameprogram. For your case:

使用该basename程序。对于您的情况:

% basename "$PWD"
bin

回答by DigitalRoss

$ echo "${PWD##*/}"

​​​​​

​​​​​

回答by mbelos

You can use a combination of pwd and basename. E.g.

您可以组合使用 pwd 和 basename。例如

#!/bin/bash

CURRENT=`pwd`
BASENAME=`basename "$CURRENT"`

echo "$BASENAME"

exit;

回答by Orange

How about grep:

grep怎么样:

pwd | grep -o '[^/]*$'

回答by FDS

I like the selected answer (Charles Duffy), but be careful if you are in a symlinked dir and you want the name of the target dir. Unfortunately I don't think it can be done in a single parameter expansion expression, perhaps I'm mistaken. This should work:

我喜欢所选的答案 (Charles Duffy),但是如果您在符号链接的目录中并且想要目标目录的名称,请小心。不幸的是,我认为它不能在单个参数扩展表达式中完成,也许我错了。这应该有效:

target_PWD=$(readlink -f .)
echo ${target_PWD##*/}

To see this, an experiment:

为了看到这一点,一个实验:

cd foo
ln -s . bar
echo ${PWD##*/}

reports "bar"

报告“酒吧”

DIRNAME

姓名

To show the leading directories of a path (without incurring a fork-exec of /usr/bin/dirname):

显示路径的前导目录(不引起 /usr/bin/dirname 的 fork-exec):

echo ${target_PWD%/*}

This will e.g. transform foo/bar/baz -> foo/bar

这将例如转换 foo/bar/baz -> foo/bar

回答by anomal

echo "$PWD" | sed 's!.*/!!'

If you are using Bourne shell or ${PWD##*/}is not available.

如果您使用的是 Bourne shell 或${PWD##*/}不可用。

回答by rodvlopes

This thread is great! Here is one more flavor:

这个线程很棒!这是另一种口味:

pwd | awk -F / '{print $NF}'

回答by Arton Dorneles

Surprisingly, no one mentioned this alternative that uses only built-in bash commands:

令人惊讶的是,没有人提到这种仅使用内置 bash 命令的替代方案:

i="$IFS";IFS='/';set -f;p=($PWD);set +f;IFS="$i";echo "${p[-1]}"

As an added bonusyou can easily obtain the name of the parent directory with:

作为额外的奖励,您可以通过以下方式轻松获取父目录的名称:

[ "${#p[@]}" -gt 1 ] && echo "${p[-2]}"

These will work on Bash 4.3-alpha or newer.

这些将适用于 Bash 4.3-alpha 或更新版本。

回答by FireInTheSky

Use:

用:

basename "$PWD"

OR

或者

IFS=/ 
var=($PWD)
echo ${var[-1]} 

Turn the Internal Filename Separator (IFS) back to space.

将内部文件名分隔符 (IFS) 转回空格。

IFS= 

There is one space after the IFS.

IFS 后面有一个空格。