[bash] 几个以前没注意过的小知识

1.  BASH_SOURCE[0] 是啥意思,以及获取当前脚本所在目录

BASH_SOURCE[0] 等价于 BASH_SOURCE, 取得当前执行的shell文件所在的路径及文件名。

如/home/abc/test.sh 内容如下:
#!/bin/sh
echo "${BASH_SOURCE[0]}"
echo "${BASH_SOURCE]}"
echo "$( dirname "${BASH_SOURCE[0]}" )"
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo $DIR


若当前目录在/home/,执行source ./abc/test.sh, 则输出:

./abc/test.sh

./abc/test.sh

./abc/

/home/abc


总之:

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 得到shell脚本文件所在完整路径(绝对路径)及文件名(无论source,sh,.三种调用方式),且不改变shell的当前目录。

https://blog.csdn.net/zhaozhencn/article/details/21103367

2.   :- 是什么意思?

${parameter:-word} If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html

https://unix.stackexchange.com/questions/103952/meaning-of-in-bash

3.   :也可以用来注释,和#一样。。。。

猜你喜欢

转载自www.cnblogs.com/hugetong/p/9633491.html