Bash – Exporting Variables from Read

bashenvironment-variablessudo

I'm asking the user to input some data using Read that data will be save on a variable that is going to be use in another shell script. However, for some reason is not working.

This is what I got in shell script1.sh

#!/bin/bash
read -p "Enter Your Full Name: " Name
export Name
sudo bash script2.sh

Script2.sh

#!/bin/bash
echo $Name

My understanding was that if I run sudo bash script1.sh is going to take the input and make it in a variable and using export I can export this to another script.

BTW I'm using Bash Version 4.3.11

Can anyone explain me what I'm doing wrong ? My goal is to ask the user their full name and in another script use their full name.

Best Answer

No Sudo Option

You can use the source command to run another bash script in the same environment you came from. (Without launching a subprocess)

Script1.sh

#!/bin/bash
read -p "Enter Your Full Name: " Name
source script2.sh

Script2.sh

#!/bin/bash
echo $Name

--

With Sudo

The reason your example doesn't work is because of the sudo. You can use Sudo -E option to keep the enviroment variables with the super user environment.

Script1.sh

   #!/bin/bash
   read -p "Enter Your Full Name: " Name
   export Name 
   sudo -E bash script2.sh

Script2.sh

#!/bin/bash
echo $Name
Related Question