当 运行 作为另一个用户时,bashrc 文件中导出的变量不可见

Exported variable in bashrc file not visible when running as another user

在 Ubuntu 20.04LTS:

为什么没有设置变量?

> adduser --gecos ',,,' --disabled-password foouser
[...output...]
> cat > /tmp/bootstrap.sh <<EOF
  echo 'export FOO=foo' >> /home/foouser/.bashrc
  . /home/foouser/.bashrc
  echo 'sourced foouser bashrc'
  set | grep FOO
EOF
> chmod a+x /tmp/bootstrap.sh
> su - foouser -c /tmp/bootstrap.sh
[...output does not include FOO...]
> deluser --remove-home foouser

您的问题是 .bashrc 配置 显式 仅 运行 用于交互式 shell。看/home/foouser/.bashrc的顶部:

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

如果您将 set -x 添加到 /tmp/bootstrap.sh 脚本,您将在执行它时看到以下内容:

+ echo 'export FOO=foo'
+ . /home/foouser/.bashrc
++ case $- in
++ return
+ echo 'sourced foouser bashrc'
sourced foouser bashrc
+ set
+ grep FOO

你可以看到它命中了 case 语句中的 return 命令。

您可以使用 -i 选项强制进行交互式 shell:

root@ed3085a447ad:/# su - foouser -c 'bash -i -c /tmp/bootstrap.sh'
bash: cannot set terminal process group (-1): Inappropriate ioctl for device
bash: no job control in this shell
sourced foouser bashrc
FOO=foo