Linux basename Command Tutorial for Beginners (With Examples)

Linux basename Command Tutorial for Beginners (With Examples)

If you’re just starting out with Linux, chances are you may have come across the term "basename command". This command is a powerful tool that can help you manipulate file paths and extract file names from a given path. In this tutorial, we will cover the basics of the basename command and provide some examples to help you understand how it works.

What is the basename command?

The basename command is a Unix/Linux command that is used to strip directory and suffix from a given file path. It returns only the base name of the given file path. In other words, it extracts the file name from a given path and ignores the directory and any file extensions.

Syntax of the basename command:

The basic syntax of the basename command is as follows:

basename [OPTIONS] file_path

Where:

  • OPTIONS: Any additional options that you can pass to the basename command.
  • file_path: The file path from which you want to extract the file name.

Examples of using the basename command:

  1. To extract the base file name from a full file path:

    $ basename /home/user/file.txt

    Output:

    file.txt
  2. To extract the base file name from a file path containing multiple directories:

    $ basename /home/user/documents/file.doc

    Output:

    file.doc
  3. To extract the base file name from a file path with a file extension:
    $ basename /var/www/html/index.html

    Output:

    index.html

Common options used with the basename command:

Here are some common options that you can use with the basename command to customize its behavior:

  • -a, –multiple: If the file_path argument contains multiple file paths, this option will print the base name of each one on a separate line.
  • -s, –suffix=SUFFIX: This option allows you to specify a suffix that will be removed from the file name before it is displayed.
  • -z, –zero: This option prints the output as null-separated strings, which can be useful for processing the output in scripts.

Conclusion:

The basename command is a handy tool for manipulating file paths and extracting file names in Linux. By using this command, you can easily strip directory paths and file extensions from a given file path. We hope this tutorial has helped you understand the basics of the basename command and how to use it effectively in your Linux system.