shell命令之 dirname与basename 区别

一、dirname :

用法
[root@localhost scripts]# 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).

dirname的主要作用是去除当前指定文件名非目录部分,删除最后一个slashes斜杠后面的内容,只保留父目录

实例:

[root@localhost httpd]# dirname /etc/httpd/
/etc
[root@localhost httpd]# dirname /etc
/

[root@localhost httpd]# dirname /etc/httpd/conf/httpd.conf 
/etc/httpd/conf

总结,如果指定目标是包含完整路径名的文件,则输出该文件的父目录;
如果指定目标是个目录,也输出其父目录,删除最后一个斜杠后面的内容。/etc/httpd/ = /etc/httpd

常用技巧:

$(dirname $0) = dirname $0

这个命令通常写在脚本文件里,他返回这个脚本文件放置的目录。
通常在脚本中通过该命令来定位所要运行程序的相对位置。
这样脚本的可移植性就提高了,扔到任何一台服务器,都可以执行。

二、basename

用法

用于打印输出基本的文件名或目录名。
Print NAME with any leading directory components removed
与dirname相反,basename是删除指定目标前面的引导目录后,输出该目标名。

实例

[root@localhost httpd]# basename /etc/httpd/conf/httpd.conf 
httpd.conf
[root@localhost httpd]# basename /etc/httpd/
httpd
[root@localhost httpd]# basename /etc/
etc
[root@localhost httpd]# basename /etc
etc

版权声明:本文为UF147原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。