Get last dirname/filename in a file path argument in Bash

I'm trying to write a post-commit hook for SVN, which is hosted on our development server. My goal is to try to automatically checkout a copy of the committed project to the directory where it is hosted on the server. However I need to be able to read only the last directory in the directory string passed to the script in order to checkout to the same sub-directory where our projects are hosted.

For example if I make an SVN commit to the project "example", my script gets "/usr/local/svn/repos/example" as its first argument. I need to get just "example" off the end of the string and then concat it with another string so I can checkout to "/server/root/example" and see the changes live immediately.

4 Answers

basename does remove the directory prefix of a path:

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

The following approach can be used to get any path of a pathname:

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

Output:

c b a 
1

Bash can get the last part of a path without having to call the external basename:

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

To print the file name without using external commands,

Run:

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

This command must run faster than basename and dirname.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like