Bash在作为另一个用户运行时不能访问函数内部的变量



我有下面的脚本,当调用函数作为userA时,我试图访问logtime变量,但函数内的$logtime没有获得值。当我不切换用户时,这个工作。

logtime=`date +"%Y-%m-%d_%H%M%S"`
runcommand()
{
echo " Log time is $logtime"
}
export -f runcommand
su userA -c "bash -c runcommand >>  compile-$logtime.txt"

$logtime在调用userA

时没有在函数内部分配
cat compile-2022-11-07_121225.txt
Log time is

declare -f funcname释放源,当求值时,重新创建您的函数。

declare -p varname发出源代码,当求值时,将重新创建您的变量。

这两个都可以添加到您在特权边界的另一边运行的内容中。因此:

sudo -u userA bash <<EOF
$(declare -f runcommand)
$(declare -p logtime)
runcommand >>"compile-$logtime.txt" # note it's the outer shell expanding $logtime
EOF

…或者,没有heredoc(从双引号到单引号的切换让内部 shell在这里展开$logtime,与上述相反):

sudo -u userA bash -c "$(declare -f runcommand); $(declare -p logtime)"'; runcommand >>compile-$logtime.txt'

如果您坚持使用su,那么最简单的修复方法就是使用export logtime

export logtime
export -f runcommand
su userA -c 'bash -c runcommand >>"compile-$logtime.txt"'

这通常是愚蠢的,但是——您有其他一些shell调用bash,所以真正的调用看起来像sh -c 'bash -c runcommand'。去掉中间的壳会让每个人的生活更轻松。

变量将保留在运行的脚本中,即使从当前用户访问它们也是不可能的。

您可以尝试先获取脚本文件的源代码,然后再执行它

最新更新