dirname command in Linux with Examples


dirname strip last component from file name.


dirname [OPTION] NAME...


dirname prints all but the final slash-delimited component of each NAME. Slashes on either side of the final component are also removed. If the string contains no slash, dirname command prints ‘.’ (meaning the current directory).

Please note, that NAME need not be a file name, but if it is, this operation effectively lists the directory that contains the final component, including the case when the final component is itself a directory.


-z, --zero
   end each output line with NUL, not newline

--help display this help and exit

   output version information and exit


1. To display the directory name of an absolute filename or file path.

$ dirname /usr/bin/sort

'/' on either side of the last component of file name is removed in the output.

$ dirname /usr/bin/sort/
$ dirname /usr/bin//.//
$ dirname /usr/bin/../.
$ dirname /var/www/html/

2. It can take multiple file names as input. Each output is displayed on a separate line.

$ dirname /var/www/html /usr/bin/sort

3. Use -z or --zero option to output a zero byte (ASCII NUL) at the end of each line, rather than a newline. This option enables other programs to parse the output even when that output would contain data with embedded newlines.

$ dirname --zero /var/www/html /usr/bin/sort
$ dirname --zero /var/www/html /usr/bin/sort|od -bc
0000000 057 166 141 162 057 167 167 167 000 057 165 163 162 057 142 151
            /   v   a   r   /   w   w   w  \0   /   u   s   r   /   b   i
0000020 156 000
            n  \0

We can see in the output of od command that two directory names are separated by a null character.

Kickstart Your Career

Get certified by completing the course

Get Started