Coder Perfect

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


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
$ echo "/server/root/$(basename /usr/local/svn/repos/example)"

Answered by sth

Solution #2

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

echo $(basename $some_path)
echo $(basename $(dirname $some_path))
echo $(basename $(dirname $(dirname $some_path)))



Answered by Jingguo Yao

Solution #3

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


Answered by Dennis Williamson

Solution #4

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


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

This command must execute more quickly than basename and dirname.

Answered by Mostafa Wael

Post is based on