Use dirname and basename for dealing with paths

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

Get last directory

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

Get all directories except the last directory

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

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

pi@pelion /var/run $ realpath shm