“cd -P”/“pwd -P”代码做什么“$(basename - ”$ BASH_SOURCE“)”没有?

时间:2017-03-31 23:27:26

标签: bash shell sh

我正在为spark阅读环境变量setup shell程序。我不太明白这一部分。

代码如下所示:

# resolve links - $0 may be a softlink
this="${BASH_SOURCE:-$0}"
common_bin="$(cd -P -- "$(dirname -- "$this")" && pwd -P)"
script="$(basename -- "$this")"
this="$common_bin/$script"

# convert relative path to absolute path
config_bin="`dirname "$this"`"
script="`basename "$this"`"
config_bin="`cd "$config_bin"; pwd`"
this="$config_bin/$script"

export SPARK_PREFIX="`dirname "$this"`"/..
export SPARK_HOME="${SPARK_PREFIX}"
export SPARK_CONF_DIR="${SPARK_CONF_DIR:-"$SPARK_HOME/conf"}"
# Add the PySpark classes to the PYTHONPATH:
export PYTHONPATH="$SPARK_HOME/python:$PYTHONPATH"
export PYTHONPATH="$SPARK_HOME/python/lib/py4j-0.9-src.zip:$PYTHONPATH"

在第一部分中,注释表示该部分用于解析链接,在第二部分中,它表示将相对路径转换为绝对路径。

但我认为这两个“此”之间没有任何区别:this="$common_bin/$script"this="$config_bin/$script"。我认为前4行已解析链接并给变量“this”一个绝对路径,为什么shell在第二部分再次执行相同的操作(第二个注释后的命令)?

提前致谢。

2 个答案:

答案 0 :(得分:1)

common_bin信任脚本的源位置视图是正确的。这可以是逻辑位置。

/opt/foobar-1.23/bin/something需要花费大量时间才能获得物理位置(不包括任何符号链接)。

我们假设此脚本为foobar-1.23

如果您在/opt/foobar处有/opt/foobar/bin/something的符号链接,并以config_bin运行您的脚本,则/opt/foobar-1.23/bin将包含common_bin。相比之下,/opt/foobar/bin将包含"$config_bin"

因此,当您想要编写一个特定于上述脚本运行时当前正在使用的软件版本的路径时,您可能希望使用"$common_bin";当你想要编写一个总是引用符号链接所指向的软件版本的路径时,你想要使用links ,即使该版本与那个版本不同在评估变量的时候正在运行

答案 1 :(得分:1)

虽然脚本的意图似乎正是Charles所提到的,但代码有一个问题会导致common_binconfig_bin设置为相同的值。

问题在第5行:

 this="$common_bin/$script"

这会使this指向先前从pwd -P获得的脚本的物理路径。

然后,在第8行,config_bin被设置为dirname this,这将是物理路径,而不是未解析符号链接的路径:

 config_bin="`dirname "$this"`"

因此,config_bincommon_bin都会获得相同的值。我没有看到脚本中任何其他地方使用的任何变量,因此不确定作者的真实意图是什么。似乎根本不需要以下代码部分:

# convert relative path to absolute path
config_bin="`dirname "$this"`"
script="`basename "$this"`"
config_bin="`cd "$config_bin"; pwd`"
this="$config_bin/$script"
相关问题