Coder Perfect

In Bash, get the final dirname/filename in a file path argument.

Problem

I’m attempting to construct a post-commit hook for SVN on our development server. My goal is to try to check out a copy of the committed project to the server’s hosting directory automatically. However, in order to checkout to the same sub-directory where our projects are housed, I need to be able to read only the last directory in the directory string supplied to the script.

If I make an SVN commit to the project “example,” for example, my script’s first argument is “/usr/local/svn/repos/example.” I need to remove only “example” from the end of the string and concatenate it with another string so that I may checkout to “/server/root/example” and see the changes in action right away.

Asked by TJ L

Solution #1

A path’s directory prefix is removed by basename:

$ basename /usr/local/svn/repos/example
example
$ echo "/server/root/$(basename /usr/local/svn/repos/example)"
/server/root/example

Answered by sth

Solution #2

To get any path of a pathname, use the following method:

some_path=a/b/c
echo $(basename $some_path)
echo $(basename $(dirname $some_path))
echo $(basename $(dirname $(dirname $some_path)))

Output:

c
b
a

Answered by Jingguo Yao

Solution #3

Without having to contact the external basename, Bash may acquire the last part of a path:

subdir="/path/to/whatever/${1##*/}"

Answered by Dennis Williamson

Solution #4

If you don’t want to use any external commands to output the file name,

Run:

fileNameWithFullPath="${fileNameWithFullPath%/}";
echo "${fileNameWithFullPath##*/}" # print the file name

This command must execute more quickly than basename and dirname.

Answered by Mostafa Wael

Post is based on https://stackoverflow.com/questions/3294072/get-last-dirname-filename-in-a-file-path-argument-in-bash