国际访客建议访问 Primers 编程伙伴 国际版站点 > Bash 教程 > dirname 以获得更好的体验。

# Bash 的 dirname 命令

dirname OPTION... NAME...

!subtitle:功能

提取文件路径中的目录(从文件路径中删除最后一个组成部分)。

!subtitle:类型

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

!subtitle:参数

  • OPTION 选项:

    • -z, --zero - 以空字符(\0)作为行的结尾,而不是换行符(\n

    • --help - 显示帮助

    • --version - 显示版本

  • NAME - 文件路径列表;不要求文件存在

# 示例

!subtitle:绝对路径

$ dirname /path/to/file.txt
/path/to
$ dirname /path/to
/path
$ dirname /path
/
$ dirname /         # 根目录会得到自身
/

!subtitle:相对路径

$ dirname ./path/to/file.txt
./path/to
$ dirname path/to/file.txt
path/to
$ dirname ./path/../path/to/file.txt
./path/../path/to
  • 只会删除路径的最后一个组成部分,不会简化路径

# 相关命令

命令 说明
basename 从文件路径中去除目录和后缀
realpath 解析路径

# 推荐阅读

# 手册

DIRNAME(1)                       User Commands                      DIRNAME(1)

NAME
       dirname - strip last component from file name

SYNOPSIS
       dirname [OPTION] NAME...

DESCRIPTION
       Output each NAME with its last non-slash component and trailing slashes
       removed;  if  NAME contains no /'s, output '.' (meaning the current di‐
       rectory).

       -z, --zero
              end each output line with NUL, not newline

       --help display this help and exit

       --version
              output version information and exit

EXAMPLES
       dirname /usr/bin/
              -> "/usr"

       dirname dir1/str dir2/str
              -> "dir1" followed by "dir2"

       dirname stdio.h
              -> "."

AUTHOR
       Written by David MacKenzie and Jim Meyering.

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
       basename(1), readlink(1)

       Full documentation <https://www.gnu.org/software/coreutils/dirname>
       or available locally via: info '(coreutils) dirname invocation'

GNU coreutils 9.4                 April 2024                        DIRNAME(1)
本文 更新于: 2025-11-27 09:38:14 创建于: 2025-11-27 09:38:14