【LinuxShell】dirname 常见用法

1、help信息

Develop>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/>
Report dirname translation bugs to <http://translationproject.org/team/>
For complete documentation, run: info coreutils 'dirname invocation'

2、应用场景

1)获取当前shell程序所在路径

在命令行状态下单纯执行 dirname $0 是毫无意义的。因为他返回当前路径的"."

在/root下新建xxx.sh脚本,在另外一个目录/usr/bin来执行这个文件,显示结果如下:

Develop>cat xxx.sh
#!/bin/bash
DIR=`dirname $0`
echo $DIR

Develop>/root/xxx.sh
/root
 Develop>pwd
/usr/bin
 Develop>/root/xxx.sh
/root
 Develop>

2)进入当前shell代码所在目录

Develop>cat /root/xxx.sh
#!/bin/bash
DIR=`dirname $0`
cd $DIR
echo `pwd`

 Develop>pwd
/usr/bin
 Develop>/root/xxx.sh
/root

 Develop>pwd
/usr/bin
 Develop>

看上面的实操可以看出,执行脚本之后,已经从之前的/usr/bin 进入/root 了。当然也仅限于在shellcode执行时进入对应目录,结束运行后实际的代码目录并未改变。

上面跳转代码也可以直接写:

cd `dirname $0`
  • $0:当前Shell程序的文件名

在可移植方面来说,这种写法不用考虑脚本实际的目录所在,比较方便

3、引申

  • 【`】,学名叫“倒引号”, 如果被“倒引号”括起来, 表示里面需要执行的是命令。
  • 【“”】 , 被双引号括起来的内容, 里面 出现 $ (美元号: 表示取变量名) `(倒引号: 表示执行命令) \(转义号: 表示转义), 其余的才表示字符串。
  • 【’‘】, 被单引号括起来的内容, 里面所有的都表示串, 包括上面所说的三个特殊字符。
posted @ 2021-04-20 11:19  恩赐解脱ゞ  阅读(1082)  评论(0编辑  收藏  举报