dirname command in Linux with Examples



Name

dirname strip last component from file name.

Synopsis

dirname [OPTION] NAME...

Description

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.

Options

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

--help display this help and exit

--version
   output version information and exit

Examples

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

$ dirname /usr/bin/sort
/usr/bin

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

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

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

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

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
/var/www/usr/bin
$ 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
0000022
$

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

Advertisements