Home > Net >  Bash cannot access a variable inside function when running as another user
Bash cannot access a variable inside function when running as another user

Time:11-08

I have the below script and I am trying to access logtime variable when calling the function as userA but the $logtime inside the function is not getting the value. This works when I am not switching the user.

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 is not getting assigned inside the function when called as userA

cat compile-2022-11-07_121225.txt
Log time is

CodePudding user response:

declare -f funcname emits source that, when evaluated, recreates your function.

declare -p varname emits source that, when evaluated, recreates your variable.

These both can be added into the content you run on the other side of a privilege boundary. Thus:

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

...or, without the heredoc (the switch from double to single quotes lets the inner shell expand $logtime here, contrary to the above):

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

If you do stick with su, though, the easiest fix is just to export logtime.

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

This is generally silly, though -- you have some other shell invoking bash, so the real invocation looks like sh -c 'bash -c runcommand'. Taking out the shell in the middle makes life easier for everyone.

CodePudding user response:

Variables will remain inside of the running scritp, even accessing them from the current user, won't be possible.

you may try to first source the script file, then execute it

  • Related