The basename
command in Bash is used to strip the directory and suffix from filenames, returning just the filename portion. This is particularly useful when you need to extract the name of a file from its full path.
The basic syntax of the basename
command is as follows:
basename [options] [arguments]
-a
: Treat each argument as a separate name and return the basename for each.-s
: Remove a specified suffix from the filename.--help
: Display help information about the command.basename /home/user/documents/file.txt
Output:
file.txt
basename /home/user/documents/file.txt .txt
Output:
file
basename -a /home/user/documents/file1.txt /home/user/documents/file2.txt
Output:
file1.txt
file2.txt
basename
with a variable:
FILE_PATH="/home/user/documents/file.txt"
basename "$FILE_PATH"
Output:
file.txt
basename
to avoid issues with spaces in filenames.-s
option when you need to remove specific extensions from multiple files efficiently.basename
with other commands like find
or xargs
for powerful file manipulation in scripts.