basename - macOS
Overview
basename
is a command-line utility in macOS that strips directory and suffix from a given file path. Essentially, it extracts the file name from a fully qualified path. This command is particularly useful in scripting and programming environments where you need to manipulate file paths or when dealing with logs and outputs that include full path specifications.
Syntax
The basic syntax of the basename
command is:
basename [path] [suffix]
Arguments:
- path: The full path from which the base name will be extracted.
- suffix: Optional. A suffix to remove from the base name.
Multiple paths can be processed in one invocation by using the following syntax:
basename -a [path1] [path2] ...
Options/Flags
-a, --multiple
: Allows the processing of multiple arguments. Each argument is treated as a separate path.-s, --suffix SUFFIX
: Removes a trailing suffix from the file name. This is useful for stripping file extensions or specific patterns.-z, --zero
: End each output line with NUL, not newline. This is helpful when dealing with file names that contain newlines.
Examples
-
Simple Extraction
basename /usr/local/bin/basename
Output:
basename
-
With Suffix Removal
basename /example/path/file.txt .txt
Output:
file
-
Multiple Arguments
basename -a /usr/local/bin/script.sh /home/user/photo.jpg
Output:
script.sh photo.jpg
-
Using with Zero Option
basename -z /data/files/example.txt
(Output would be
example.txt
followed by a null character).
Common Issues
- Incorrect Path: Users sometimes mistakenly use
basename
on directories. Remember,basename
is intended for file paths. - Suffix Not Matching: The suffix passed to
basename
must exactly match the end of the base name, or it will not be stripped.
Integration
basename
is often used in scripting and combined with other commands:
Example with find
to change extensions:
for file in $(find . -type f -name "*.txt"); do
mv "$file" "$(dirname "$file")/$(basename "$file" .txt).md"
done
This script finds all .txt
files and renames them to .md
, keeping them in the same directory.
Related Commands
dirname
: Outputs the path part of the given file argument, which complementsbasename
by extracting the directory path.pathchk
: Checks the portability of file names, useful in scripts validating file paths.
For further reading and more detailed information, consult the basename
manpage on your system using man basename
or visit the online macOS command reference.