Issue
On Ubuntu 20.04LTS:
- Create a dummy user.
- Create a short script that appends an exported variable to the new user's
.bashrc
, then sources that.bashrc
and tries to use the variable. - Run the script as the new user.
Why is the variable not set?
> 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
Solution
Your problem is that .bashrc
is configure explicitly to only run for interactive shells. Look at the top of /home/foouser/.bashrc
:
# If not running interactively, don't do anything
case $- in
*i*) ;;
*) return;;
esac
If you add a set -x
to your /tmp/bootstrap.sh
script, you will see when you execute it the following:
+ echo 'export FOO=foo'
+ . /home/foouser/.bashrc
++ case $- in
++ return
+ echo 'sourced foouser bashrc'
sourced foouser bashrc
+ set
+ grep FOO
There you can see it hits the return
command in the case statement.
You can force an interactive shell with the -i
option:
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
Answered By - larsks Answer Checked By - Mildred Charles (WPSolving Admin)