1. 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 separate output with NUL rather than 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: <http://www.gnu.org/software/coreutils/>
For complete documentation, run: info coreutils 'dirname invocation'
手册页“Print NAME with its trailing /component removed; if NAME contains no /’s, output ‘.’ (meaning the current directory).”该命令可以取给定路径的目录部分(strip non-directory suffix from file name)。这个命令很少直接在shell命令行中使用,一般把它用在shell脚本中,用于取得脚本文件所在目录,然后将当前目录切换过去。
★常用示例
示例一: # /usr/bin为获取到的目录
[root@local ~]# dirname /usr/bin/sort
/usr/bin
示例二: # 如无/则获取当前目录.
[root@local ~]# dirname stdio.h
.
示例三: # 含/和无/,其结果和不含/效果一样的
[root@local ~]# dirname /usr/bin
/usr
[root@local ~]# dirname /usr/bin/
/usr
示例四: # 获取多个目录列表,以换行为分隔
[root@local ~]# dirname dir1/file1 dir2/file2
dir1
dir2
示例五: # 获取多个目录列表,以NUL为分隔
[root@local ~]# dirname -z dir1/file1 dir2/file2
dir1dir2
★脚本用法
!/bin/bash
# 跳转到脚本所在目录
cd $(dirname "$0") || exit 1
# 对上面的脚本的解释
$0 当前Shell程序的文件名
dirname $0 获取当前Shell程序的路径
cd $(dirname $0) 进入当前Shell程序的目录
exit 1 如果获取不到则退出脚本
2. basename
# 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
-z, --zero separate output with NUL rather than 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: <http://www.gnu.org/software/coreutils/>
For complete documentation, run: info coreutils 'basename invocation'
basename命令用于去掉文件名的目录和后缀(strip directory and suffix from filenames),对应的dirname命令用于截取目录
★常用示例
示例一 # 获取到最后文件名sort
[root@local ~]# basename /usr/bin/sort
sort
示例二 # 去除文件名后缀
[root@local ~]# basename /usr/include/stdio.h .h
stdio
[root@local ~]# basename /usr/include/stdio.h stdio.h
stdio.h
示例三 # 去除文件名后缀方式的另外一种方法
[root@local ~]# basename -s .h /usr/include/stdio.h
stdio
示例四 # 获取多个目录下的文件列表,以换行符\n为分隔
[root@local ~]# basename -a dir1/file1 dir2/file2
file1
file2
示例五 # 获取多个目录下的文件列表,以NUL为分隔
[root@local ~]# basename -a -z dir1/file1 dir2/file2
file1file2
————————————————
版权声明:本文为CSDN博主「杰瑞26」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Jerry_1126/article/details/79872110
浙公网安备 33010602011771号