Previous Table of Contents Next

Module 8


The external basename command parses the given path and returns only the filename. Any prefix ending in / (slash) is deleted from the path. If a second argument is present, it is used as a suffix to be deleted from the filename. For instance, the command

     cj> basename /u1/ts/mylogin/junk.c \.c

returns junk. The entire path (/u1/tech/mylogin/) and the .c suffix are removed.

The longest possible prefix is removed while the shortest possible suffix is deleted.


Following is the format of the basename command.

     basename path [ suffix ]


Only two arguments may be passed to the basename command.

path The path that is parsed with only the filename being returned.
suffix A suffix string that is removed from the end of the filename.


Refer to the dirname command described in Module 35.


The basename command writes to the standard output.


The basename command is normally used as a substitution command within a shell script. It can be used to reduce a full path parameter or variable down to a single filename. It can also remove suffixes so a single parameter variable can be used to perform a task that uses the same filename with different suffixes.


In this activity you use the basename command to copy a file to a different directory and name. Begin at the shell prompt.

1.  Type cd /tmp and press Return. This puts you in the /tmp directory just to force the use of paths in the following command.
2.  Type cp $HOME/file1 `basename $HOME/file1 1`.bak and press Return.
     cj> cp $HOME/file1 `basename $HOME/file1 1`.bak

The $HOME/file1 file is copied to /tmp/file.bak. The cp command looks like cp $HOME/file1 file.bak after the basename command executes.
3.  Type rm file.bak and press Return.
4.  Type cd and press Return to return to your HOME directory.
5.  Turn to Module 35 (SV), Module 91 (BSD) to continue the learning sequence.

Previous Table of Contents Next