切换用户后如何访问相同的变量数据?例如:
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
变量。