检索保存bash脚本的文件系统位置



可能重复:
在bash脚本中,我如何知道脚本文件名?

我经常需要bash脚本的文件系统来引用其他所需的资源。通常在shebang行之后的行中使用以下代码。它设置一个名为"scriptPos"的变量,该变量包含脚本的当前路径

scriptPos=${0%/*}

它工作得很好,但有什么更直观的东西可以取代外壳扩展吗?

dirname,但它需要fork:

scriptPos=$(dirname "$0") 

一个选项是

scriptPos=$(dirname $0)

这是以额外的过程为代价的,但更具自我描述性。如果脚本直接在当前中,则输出会有所不同(在我看来是更好的):

#!/bin/bash
scriptPos=$(dirname $0)
echo '$0:' $0
echo 'dirname:' $scriptPos
echo 'expansion:' ${0%/*}
$ bash tmp.bash
$0: tmp.bash
dirname: .
expansion: tmp.bash

更新:试图解决jm666指出的缺点。

#!/bin/bash
scriptPos=$( v=$(readlink "$0") && echo $(dirname "$v") || echo $(dirname "$0") )

最新更新