The “basename” command is a utility that allows you to extract the base or file name from a given path by removing the leading directory portions. It is commonly used to obtain the filename from a full path or to remove directory prefixes from file paths.
When you provide a path to the “basename” command, it identifies the last component of the path, which is typically the filename or the name of the file or directory at the end of the path. It removes all the preceding directory portions, leaving only the base name.
For example, if you have a path “/home/user/documents/file.txt,” the “basename” command will extract “file.txt” as the base name by removing the “/home/user/documents/” portion. Similarly, if the input path is “/var/log/syslog,” the “basename” command will extract “syslog” as the base name.
The “basename” command is useful in various scenarios. It can be used in scripting or automation tasks where you need to extract only the filename from a full path. It simplifies file manipulation and helps to obtain the base name for further processing or analysis.
Additionally, the “basename” command offers options to remove specific file extensions from the base name. For example, if you have a file named “document.txt” and you want to remove the “.txt” extension, you can use the appropriate option with the “basename” command to obtain just “document” as the result.
The “basename” command can also handle multiple paths or a list of files. In such cases, it processes each input path separately and provides the corresponding base name for each entry.
To use the “basename” command, you provide the path or list of paths as arguments. The command then processes the input and prints the extracted base names to standard output.
basename Command Examples
1. Show only the file name from a path:
# basename /path/to/file
2. Show only the rightmost directory name from a path:
# basename /path/to/directory/
3. Show only the file name from a path, with a suffix removed:
# basename /path/to/file suffix
Summary
In summary, the “basename” command is a utility that removes the leading directory portions from a given path and extracts the base or file name. It is commonly used to obtain filenames from full paths or to remove directory prefixes from file paths. By simplifying file manipulation and extraction of base names, the “basename” command is a valuable tool in scripting, automation, and various file-related tasks.