我有一些自称 bash 专家创建的以下脚本:
SCRIPT_LOCATION="$(readlink -f $0)"
SCRIPT_DIRECTORY="$(dirname ${SCRIPT_LOCATION})"
export PYTHONPATH="${PYTHONPATH}:${SCRIPT_DIRECTORY}/util"
在我本地的 Ubuntu 16.04 上运行良好。现在我想在我们的 RH 7.2 服务器上使用它;然后我从 readlink
收到一条错误消息;关于使用错误参数调用。
然后我想到:在 Ubuntu 上,$0 给出“bash”;而在 RH 上,它给出“-bash”。
编辑:脚本被调用为 。我们的脚本.sh
问题:
- 知道这是为什么吗?
- 当我更改我的脚本以使用硬编码的
readlink -f bash
时,一切正常。是否有“更好”的方法来解决这个问题? - 也请随意解释 readlink -f bash 实际上在做什么 ;-)
最佳答案
由于脚本是源代码,因此 readlink -f $0
毫无意义,因为它只会向您显示用于运行您当前使用的 shell 的命令。
要解释命令的差异,请查看 bash 手册页:
A login shell is one whose first character of argument zero is a -, or one started with the --login option.
When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.
所以猜测ubuntu以noprofile选项开头。
关于readlink,我们可以再看看man page
-f, --canonicalize canonicalize by following every symlink in every component of the given name recursively; all but the last component must exist
因此它遵循指向基础的符号链接(symbolic link)。
对任何非限定路径使用 readlink -f 将导致它只是将最后一个 arg 附加到您当前的工作目录,这实际上不会显示脚本运行的位置。
尝试在其后放置任何随机字符串而不是 bash,您会发现脚本不受影响。
例如
readlink -f dafsfdsf
返回
/home/me/testscript/dafsfdsf
关于linux - $0 在 Redhat 和 Ubuntu 上给出不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39487737/