Get last dirname/filename in a file path argument in Bash
LinuxBashShellSvnLinux Problem Overview
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.
Linux Solutions
Solution 1 - Linux
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
Solution 2 - Linux
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
Solution 3 - Linux
Bash can get the last part of a path without having to call the external basename
:
subdir="/path/to/whatever/${1##*/}"
Solution 4 - Linux
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
.