Linux basename Command
Complete Linux Command Reference
What is the basename command
basenameIt is a simple but practical command-line tool in Linux systems, used to extract the filename part from a file path. It is like a path parser that strips directory information and keeps only the final filename.
Analogy: Imagine you have a complete mailing address (such as "China/Beijing/Haidian District/Zhongguancun Street No. 1"),basenamethe function of basename is to extract only the last "Zhongguancun Street No. 1" part.
Basic syntax of the basename command
basename [选项] 路径 [后缀]
Parameter description
- Path(Required): The full path string to process
- Suffix(Optional): If specified, this suffix will be removed from the result
Common options
| Option | Description |
|---|---|
-a |
Supports multiple paths as arguments |
-s 后缀 |
Remove the specified suffix (equivalent to adding the suffix parameter at the end of the command) |
-z |
Separate output results with null characters (instead of newlines) |
Basic usage examples
Example 1: Basic filename extraction
Example
report.txt
Example 2: Remove file extension
Example
report
Example 3: Process multiple files (using -a option)
Example
file1.txt
file2.log
Practical application scenarios
Scenario 1: Batch processing file extensions
Example
mv "$file" "$(basename "$file" .jpg).png"
done
Explanation: This script renames all .jpg files in the current directory to .png files, changing only the extension while keeping the original filename.
Scenario 2: Get the current script name in a script
Example
SCRIPT_NAME=$(basename "$0")
echo "Running script:$SCRIPT_NAME"
Scenario 3: Combining with the find command
Example
Purpose: Find all .log files in the /var/log directory and display only the filenames (without paths)
FAQ
Q1: What is the difference between basename and dirname?
| Command | Function | Example input | Example output |
|---|---|---|---|
basename |
Extract the last part of the path | /a/b/c.txt | c.txt |
dirname |
Extract the directory part | /a/b/c.txt | /a/b |
Q2: Why doesn't my basename command work?
Common reasons:
The path contains special characters (such as spaces) but is not quoted
- Incorrect:
basename /path/with spaces/file - Correct:
basename "/path/with spaces/file"
- Incorrect:
Using variables without quotes in scripts
- Incorrect:
basename $filepath - Correct:
basename "$filepath"
- Incorrect:
Advanced tips
Tip 1: Handling multiple suffixes
Example
archive.tar
$ basename archive.tar.gz .tar.gz
archive
Tip 2: Using in a pipeline
Example
Output:python
Tip 3: Alternative using parameter expansion
In Bash, you can also use parameter expansion to achieve similar functionality:
Example
filename="${path##*/}" # Equivalent to basename
echo "$filename"
Other extensions