basename & dirname : NIX classes
May 18, 2012 Leave a comment
Here I am going to describe some commands which can help us in day to day task.
The basename command will strip off the directory portion of a filename path and return only the filename itself. In the following example, basename is used to strip the directory path from the filename so it returns simply dfs.sh.
linux@atul $ basename /home/atul/script/WORKING_FINE/dfs.sh dfs.sh
The basename utility also allows the extension or suffix to be stripped from a file basename. The extension to be stripped is added after the file path. In the following example, .sh is added after the filename. The return from basename is the single word file:
linux@atul $ basename /home/atul/script/WORKING_FINE/dfs.sh .sh dfs
The dirname utility is the complement of basename. It returns the “path” component of a file pathname string, as shown in the following listing. In the second dirname example, dirname also removes the trailing slash before attempting to understand the string. The result is that the dirname portion of
linux@atul $ dirname /home/atul/script/WORKING_FINE/dfs.sh /home/atul/script/WORKING_FINE
dirname has no options for the command and simply returns the directory portion of a file path. It is not used as often as basename.