简体   繁体   中英

Get current directory or folder name (without the full path)

How could I retrieve the current working directory/folder name in a bash script, or even better, just a terminal command.

pwd gives the full path of the current working directory, eg /opt/local/bin but I only want bin .

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 :

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.

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 support to work even with multiple trailing slashes:

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"

Alternatively, without 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

Use the basename program. For your case:

% basename "$PWD"
bin
$ echo "${PWD##*/}"

​​​​​​​

Use:

basename "$PWD"

OR

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

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

IFS= 

There is one space after the IFS.

You can use a combination of pwd and basename. Eg

#!/bin/bash

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

echo "$BASENAME"

exit;

grep怎么样:

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

或者

echo "$(basename $(pwd))"

This thread is great! Here is one more flavor:

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

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:

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):

echo ${target_PWD%/*}

This will eg transform foo/bar/baz -> foo/bar

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

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

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

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

As an added bonus you 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.

有很多方法我特别喜欢查尔斯的方式,因为它避免了一个新的过程,但在知道这一点之前,我用 awk 解决了它

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

对于像我这样的寻找骑师:

find $PWD -maxdepth 0 -printf "%f\n"

i usually use this in sh scripts

SCRIPTSRC=`readlink -f "$0" || echo "$0"`
RUN_PATH=`dirname "${SCRIPTSRC}" || echo .`
echo "Running from ${RUN_PATH}"
...
cd ${RUN_PATH}/subfolder

you can use this to automate things ...

Just use:

pwd | xargs basename

or

basename "`pwd`"

在带有正则表达式的 grep 下也可以正常工作,

>pwd | grep -o "\w*-*$"

If you want to see only the current directory in the bash prompt region, you can edit .bashrc file in ~ . Change \w to \W in the line:

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

Run source ~/.bashrc and it will only display the directory name in the prompt region.

Ref: https://superuser.com/questions/60555/show-only-current-directory-name-not-full-path-on-bash-prompt

我非常喜欢使用gbasename ,它是 GNU coreutils 的一部分。

Just run the following command line:

basename $(pwd)

If you want to copy that name:

basename $(pwd) | xclip -selection clipboard

在此处输入图像描述

An alternative to basname examples

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

OR

pwd | ack -o "[^/]+$"

My shell did not come with the basename package and I tend to avoid downloading packages if there are ways around it.

您可以使用 basename 实用程序从字符串中删除任何以 / 结尾的前缀和后缀(如果存在于字符串中),并在标准输出上打印结果。

$basename <path-of-directory>

The following commands will result in printing your current working directory in a bash script.

pushd .
CURRENT_DIR="`cd $1; pwd`"
popd
echo $CURRENT_DIR

Just remove any character until a / (or \ , if you're on Windows). As the match is gonna be made greedy it will remove everything until the last / :

pwd | sed 's/.*\///g'

In your case the result is as expected:

λ a='/opt/local/bin'

λ echo $a | sed 's/.*\///g'
bin

我使用以下命令:

dirname "$0"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM