basename和dirname命令

-- TOC --

basename是指去掉路径名后剩下纯文件名,basename命令就是用来获取这个名字,相对而言,理解dirname。

basename

$ basename ~/test/test.c
test.c

这是一个比较简单的命令,在编写复杂shell脚本的时候,这类简单的命令很有用处。

$ basename --help
Usage: basename NAME [SUFFIX]
  or:  basename OPTION... NAME...
Print NAME with any leading directory components removed.
If specified, 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"

GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Full documentation at: <https://www.gnu.org/software/coreutils/basename>
or available locally via: info '(coreutils) basename invocation'

注意:

  1. -s参数后先跟后缀字符串;
  2. 貌似name只是个字符串,不需要它存在硬盘上!
$ basename /abc/def/kkk
kkk

dirname

$ dirname --help
Usage: dirname [OPTION] NAME...
Output each NAME with its last non-slash component and trailing slashes
removed; if NAME contains no /'s, output '.' (meaning the current directory).

  -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            -> "."

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

本文链接:https://cs.pynote.net/sf/linux/shell/202111237/

-- EOF --

-- MORE --