3371

17 分钟

#Bash 的 basename 命令

basename OPTION... NAME [SUFFIX]

功能

从文件路径中去除目录和后缀。

类型

可执行文件(/usr/bin/basename),属于 coreutils

参数

  • OPTION 选项:
    • -a, --multiple - 输入多个文件名参数,而不是要删除的后缀
    • -s, --suffix=SUFFIX - 删除后缀的 SUFFIX
    • -z, --zero - 以空字符(\0)作为行的结尾,而不是换行符(\n
    • --help - 显示帮助
    • --version - 显示版本
  • NAME - 文件路径;不要求文件存在
  • SUFFIX - 要删除的后缀;同 -s 选项

#示例

单个文件

$ basename /path/to/file.txt # 去除目录 rgb.txt $ basename /path/to/file.txt .txt # 去除目录和后缀

多个文件

$ basename -a /path/to/file1.txt /path/to/file2.txt # 去除目录 file1.txt file2.txt $ basename -s .txt -a /path/to/file1.txt /path/to/file2.txt # 去除目录和后缀 file1 file2
  • -s 选项参数必须在 -a 选项之前,否则 -a 会将 -s.txt 也视为两个文件路径参数

#相关命令

命令说明
dirname提取文件路径中的目录

#推荐阅读

#手册

BASENAME(1) User Commands BASENAME(1) NAME basename - strip directory and suffix from filenames SYNOPSIS basename NAME [SUFFIX] basename OPTION... NAME... DESCRIPTION Print NAME with any leading directory components removed. If speci‐ fied, also remove a trailing SUFFIX. Mandatory arguments to long options are mandatory for short options too. -a, --multiple support multiple arguments and treat each as a NAME -s, --suffix=SUFFIX remove a trailing SUFFIX; implies -a -z, --zero end each output line with NUL, not newline --help display this help and exit --version output version information and exit EXAMPLES basename /usr/bin/sort -> "sort" basename include/stdio.h .h -> "stdio" basename -s .h include/stdio.h -> "stdio" basename -a any/str1 any/str2 -> "str1" followed by "str2" AUTHOR Written by David MacKenzie. REPORTING BUGS GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT Copyright © 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO dirname(1), readlink(1) Full documentation <https://www.gnu.org/software/coreutils/basename> or available locally via: info '(coreutils) basename invocation' GNU coreutils 9.4 April 2024 BASENAME(1)

创建于 2025/10/29

更新于 2025/10/29