Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable is not being echoed

Tags:

linux

bash

When I run the following script in Bash 3.2.48:

#!/bin/bash

export var1='var1'
echo "UID=$UID"

if [ x"$UID" != x"0" ]
then
    export var2='var2'
    while ! { sudo -v; }; do { sudo -v; }; done;
    sudo $0
    exit
fi

echo $var1
echo $var2

exit 0

What I get as output is:

UID=1000
UID=0
var1

Why is var2 not exported and echoed? I'm pretty sure that the same script worked with older Bash versions.


1 Answers

  • you enter first time with UID == 1000, you enter the if clause
  • you sudo to execute the script with UID == 0; sudo doesn't preserve the environment if env_reset is set in /etc/sudoers (default in most distros). You need sudo -E to preserve env.
  • you exit (before echoing)

from the sudo call you enter with clean env.

  • you enter with UID == 0
  • you don't enter the if clause, var2 is not set
  • you echo the variables.
like image 50
vartec Avatar answered Mar 08 '26 01:03

vartec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!