## 36.13. Using basename and dirname

Almost every Unix command can use relative and absolute pathnames (Section 31.2) to find a file or directory. There are times you'll need part of a pathname -- the head (everything before the last slash) or the tail (the name after the last slash). The utilities basename and dirname, available on most Unix systems, handle that.

### 36.13.1. Introduction to basename and dirname

The basename command strips any "path" name components from a filename, leaving you with a "pure" filename. For example:

>     % basename /usr/bin/gigiplot
>     gigiplot
>     % basename /home/mikel/bin/bvurns.sh
>     bvurns.sh

basename can also strip a suffix from a filename. For example:

>     % basename /home/mikel/bin/bvurns.sh .sh
>     bvurns

The dirname command strips the filename itself, giving you the "directory" part of the pathname:

>     % dirname /usr/bin/screenblank
>     /usr/bin
>     % dirname local
>     .

If you give dirname a "pure" filename (i.e., a filename with no path, as in the second example), it tells you that the directory is . (the current directory).

> NOTE: dirname and basename have a bug in some implementations. They don't recognize the second argument as a filename suffix to strip. Here's a good test:

> >     % basename 0.foo .foo

> If the result is `0`, your basename implementation is good. If the answer is `0.foo`, the implementation is bad. If basename doesn't work, dirname won't, either.

### 36.13.2. Use with Loops

Here's an example of basename and dirname. There's a directory tree with some very large files -- over 100,000 characters. You want to find those files, run split (Section 21.9) on them, and add huge. to the start of the original filename. By default, split names the file chunks xaa, xab, xac, and so on; you want to use the original filename and a dot (.) instead of x:

`||` Section 35.14, `exit` Section 35.16

>     for path in `find /home/you -type f -size +100000c -print`
>     do
>         cd `dirname $path` || exit
>         filename=`basename $path`
>         split $filename $filename.
>         mv -i $filename huge.$filename
>     done

The find command will output pathnames like these:

>     /home/you/somefile
>     /home/you/subdir/anotherfile

(The absolute pathnames are important here. The cd would fail on the second pass of the loop if you use relative pathnames.) In the loop, the cd command uses dirname to go to the directory where the file is. The filename variable, with the output of basename, is used several places -- twice on the split command line.

If the previous code results in the error `command line too long`, replace the first lines with the two lines below. This makes a redirected-input loop:

>     find /home/you -type f -size +100000c -print |
>     while read path

--JP and ML

Copyright © 2003 O'Reilly & Associates. All rights reserved.