linux - $0 在 Redhat 和 Ubuntu 上给出不同的结果?

标签 linux bash ubuntu redhat

我有一些自称 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

问题:

  1. 知道这是为什么吗?
  2. 当我更改我的脚本以使用硬编码的readlink -f bash 时,一切正常。是否有“更好”的方法来解决这个问题?
  3. 也请随意解释 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/

相关文章:

c - 为私钥分配内存的合理安全、合理便携的方法是什么?

linux - 没有 Kerberos 的调度 crontab

linux - 如何获取从 Rust 程序内部运行的 Bash 脚本的退出代码?

ubuntu - 在 neo4j-service 中设置 ulimit 是一种可接受的方法吗

linux - 运行 apt-get upgrade 后如何避免 GRUB 错误 - Ubuntu

Linux:我应该使用什么来运行基于日历系统的终端程序?

linux - 我有一个 jailed 用户,无法 ping 通主机名(仅限 IP 地址)

regex - 使用 sed 和 mv 命令取消隐藏 unix 中的隐藏文件

linux - 无法通过 expect 对 bash 命令脚本进行 SSH

svn - 在颠覆中搬迁而不搬迁?