我不知道如何更好地描述我刚刚经历的行为。我从 this 答案到达,因为我正在尝试将文件的内容读入字符串中。
我有以下可执行脚本:
root@host:~# pwd
/root
root@host:~# ls -l script.sh
-rwxr-xr-x 1 root root 83 Mar 7 21:25 script.sh
root@host:~# cat script.sh
#!/usr/bin/env bash
set -e
echo $SHELL
echo "foo" > /root/BAR
echo "$(</root/BAR)"
现在,当我使用当前的
bash
实例执行此操作或将其显式传递给 /bin/bash
时,它会按预期执行:
root@host:~# echo $SHELL
/bin/bash
root@host:~# ./script.sh
/bin/bash
foo
root@host:~# /bin/bash script.sh
/bin/bash
foo
root@host:~#
但是,当我使用
sh
启动脚本时,我得到以下输出(未读取文件),尽管它看起来正在使用预期的 shell:
root@host:~# sh script.sh
/bin/bash
root@host:~#
从 this 答案中我认为环境变量
$SHELL
可能不可靠,事实证明确实如此。当我在脚本中运行 ps -o command -p $$
时,它会打印
COMMAND
sh script.sh
这让我认为 shebang 被忽略了?
有人可以向我解释一下发生了什么事吗?
至于没有
cat
的文件读取,我想我只需将脚本显式调用为 bash script.py
即可。
你是对的,在某些系统上,
/bin/sh
可能是指向非常基本的 Bourne shell 解释器的符号链接。该解释器可能根本不理解 shebang 行,而只是执行脚本本身。