0

I have this very simplified bash script that calls itself and not able to keep the exported variable id to the child script :

  1 #! /bin/bash
  2 
  3 SCRIPT="$(realpath "${0}")"
  4 
  5 echo "start script"
  6 echo "euid= $EUID"
  7 
  8 if [ $EUID != 0 ]; then
  9 
 10         export id=$EUID
 11         sudo ${SCRIPT}
 12         exit 0
 13 fi
 14 
 15 echo "HERE WE ARE ROOT"
 16 echo "euid= $EUID"
 17 echo "id= $id"
 18 
 19 exit 0

The output is :

start script
euid= 1000
start script
euid= 0
HERE WE ARE ROOT
euid= 0
id= 

The EUID of the regular user is 1000 and what i am trying to do is to keep this EUID in the child process that is run as root.

id is unbound in the child script.

So i have done a simple test with an interactive shell :

$ export var=1
$ /bin/bash
$ echo $var
1
$ var=2
$ echo $var
2
$ exit
$ echo $var
1

and var is correctly exported here, but not in the other case, what's the difference ?

I guess i am missing something obvious as i am pretty unexperienced in shell scripting.

Thanks.

Fryz
  • 2,119
  • 2
  • 25
  • 45

1 Answers1

1

For security reasons, you can't "inject" an environment variable into a sudo session. You can check if your system supports the following sudo flag:

 -E, --preserve-env
             Indicates to the security policy that the user wishes to pre‐
             serve their existing environment variables.  The security
             policy may return an error if the user does not have permis‐
             sion to preserve the environment.

Otherwise, you will make your own life much easier, if you just pass the variables through command line arguments.

Pavel
  • 7,436
  • 2
  • 29
  • 42