Loading...

Use dirname and basename for dealing with paths

:heavy_exclamation_mark: This post is older than a year. Consider some information might not be accurate anymore. :heavy_exclamation_mark:

Dealing with paths or pathnames is a common Bash Shell scripting task. dirname and basename are unix programs that are very handy for dealing with pathnames.

Getting current path with pwd (print working directory).

root@cinhtau:/var/log/apache2# pwd
/var/log/apache2

Get last directory

root@cinhtau:/var/log/apache2# basename $(pwd)
apache2

Get all directories except the last directory

root@cinhtau:/var/log/apache2# dirname $(pwd)
/var/log

If you deal with symbolic links, you can use realpath to get the absolute pathname.

pi@pelion /var/run $ realpath shm
/dev/shm