linux - 为什么指定我的 shell 会更改 root 的 EUID?

标签 linux bash shell sudo ubuntu-14.04

如果我在脚本中将我的 shell 指定为/bin/bash,则 root 的 EUID 为 0。如果我不这样做,并且脚本在我的默认 shell(也是/bin/bash)中运行,则 root 的 EUID root 是一个空字符串!我是脚本新手,认为只要 bash 运行就没有区别。

我正在运行的代码检查程序是否由 root 运行,如果不是,则以 sudo 身份重新启动程序。

#!/bin/bash
echo euid = $EUID
echo shell = $SHELL

if [ $EUID -ne 0 ]; then
    sudo "$0"
    exit $?
fi

运行时,我看到了

euid = 1000
shell = /bin/bash
euid = 0
shell = /bin/bash

但是如果我删除 she-bang 行,我会得到

euid = 1000
shell = /bin/bash
euid =
shell = /bin/bash
./test.sh: 4: [: -ne: unexpected operator

该脚本四次都在同一个 shell 中运行,那么为什么当 sudo 在不指定/bin/bash 的情况下调用它时它的行为不同?

如果重要的话,我正在运行 Ubuntu 14.04。

提前致谢!

最佳答案

通过删除 shebang 行,您将调用 Ubuntu 默认 shell,即 Dash,而不是 Bash。

Dash 没有定义 $EUID,导致空赋值。事实上,$EUID 是 Bash 对 POSIX 标准带来的众多增强功能之一。相反,Dash 旨在尽可能小巧、快速和轻便,并且仅实现标准所需的最少功能集。

您断言它四次都在同一个 shell 中运行,但实际上并非如此。环境变量$SHELL 不是指运行当前进程的shell;它指的是您帐户的登录 shell,在 /etc/passwd 或等效项中定义。

关于linux - 为什么指定我的 shell 会更改 root 的 EUID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24295045/

相关文章:

linux - makefile 不生成可执行文件

linux - Nginx 无法启动。/usr/sbin/nginx 和/var/run/nginx.pid 不存在

python - gunicorn - 如果从 shell 脚本执行则不获取配置文件

python - 1 周内修改的文件名列表

linux - 如何在kali linux 2020.1中以root身份登录?

linux - 依靠/proc/[pid]/status 来检查另一个进程的身份

bash - 为什么在 crontab 中调用时使用 set -e 会导致我的脚本失败?

linux - 如何在 Linux/Unix 终端中开始和停止打印具有特定文本的行

linux - 意外的 EOF 错误

bash - 使用函数中止 bash 脚本