basename – strip directory and suffix from a full path to a file

basename is a very simple but useful Unix command which is used mostly in shell scripting. Taking a full path to a file as a parameter, it then stips the directory names from it and returns you just the name of a file.

Note: basename is a string stripping command – it simply returns you the last portion of a provided full path. It does not verify whether this portion is an actual file.

How to use basename command

This is how basename is invoked:

ubuntu$ basename /etc/network/if-down.d/postfix
postfix

basename in shell scripting

An example of using the basename command is shown below. This command line takes the input from a standard output from the find command and outputs only the names of the files. While there's not much practicality in doing this, it's a great way to show how basename works.

Here's the standard find output:

ubuntu$ find /etc/network/
/etc/network/
/etc/network/if-down.d
/etc/network/if-down.d/wpasupplicant
/etc/network/if-down.d/postfix
/etc/network/if-post-down.d
/etc/network/if-post-down.d/wpasupplicant
/etc/network/if-post-down.d/wireless-tools
/etc/network/if-pre-up.d
/etc/network/if-pre-up.d/wpasupplicant
/etc/network/if-pre-up.d/wireless-tools
/etc/network/if-up.d
/etc/network/if-up.d/wpasupplicant
/etc/network/if-up.d/mountnfs
/etc/network/if-up.d/ntp
/etc/network/if-up.d/ntpdate
/etc/network/if-up.d/postfix
/etc/network/interfaces

And this is how only the filenames are extracted. Note, how for some parameters you see not the filenames, but directory names like if-down.d, simply because they're the last part of a string returned by the find output:

ubuntu$ for f in `find /etc/network/`; do basename $f; done;
network
if-down.d
wpasupplicant
postfix
if-post-down.d
wpasupplicant
wireless-tools
if-pre-up.d
wpasupplicant
wireless-tools
if-up.d
wpasupplicant
mountnfs
ntp
ntpdate
postfix
interfaces

See also:

  • dirname – extract the directory name from a full path
  • cd – change directory
  • pwd – confirm the current directory you’re in

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS