![如何在更改用户后保留脚本中的 shell 变量](https://linux22.com/image/146775/%E5%A6%82%E4%BD%95%E5%9C%A8%E6%9B%B4%E6%94%B9%E7%94%A8%E6%88%B7%E5%90%8E%E4%BF%9D%E7%95%99%E8%84%9A%E6%9C%AC%E4%B8%AD%E7%9A%84%20shell%20%E5%8F%98%E9%87%8F.png)
切换用户后如何访问相同的变量数据?例如:
artifact=archive.tar.gz
workdir=/home/user
echo "$workdir/$artifact"
sudo -u otheruser bash
echo "$workdir/$artifact"
生产:
/home/user/archive.tar.gz
/
第二个是否有可能echo
以与第一个相同的路径解析?
编辑:完整的解决方案,感谢@Romeo Ninov 和@steeldriver:
export artifact=archive.tar.gz
export workdir=/home/user
echo "$workdir/$artifact"
sudo -Eu otheruser bash
echo "$workdir/$artifact"
答案1
导出变量:
export artifact=archive.tar.gz
export workdir=/home/user
答案2
您可能想要使用支持更改 uids 和 gids 的zsh
代替bash
(前提是它以超级用户权限启动):
#! /bin/zsh -
id
echo "Original user: $SUDO_USER"
var=test
(
USERNAME=$SUDO_USER
echo "Runing as $(id -un) in this subshell var=$var"
)
(USERNAME=nobody; echo and now:; id; echo $var)
运行为:
$ sudo ./that-script
uid=0(root) gid=0(root) groups=0(root)
Original user: stephane
Runing as stephane in this subshell var=test
and now:
uid=65534(nobody) gid=65534(nogroup) groups=65534(nogroup)
test
设置USERNAME
设置 uid、euid、gid、egid 和补充 gid,就像登录或使用sudo
.您还可以单独设置UID
// EUID
...GID
变量。