Get last dirname/filename in a file path argument in Bash
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
Bash can get the last part of a path without having to call the external basename
:
dir="/path/to/whatever/"
dir="${dir%/}" # strip trailing slash (if any)
subdir="${dir##*/}"
This uses Bash's parameter expansion to remove the part of the string before the last (remaining) slash.
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
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
.