2

I have created a script to download Terraform onto my server and install it.

#!/bin/bash

wget https://releases.hashicorp.com/terraform/0.7.0/terraform_0.7.0_linux_amd64.zip

unzip terraform_0.7.0_linux_amd64.zip

echo "export PATH=$PATH:/root/terraform_dir" >> /root/.bash_profile

source /root/.bash_profile

terraform --version

This code is working perfectly. But once the script is completed and comes out, the .bash_profile file is back at its original state. i.e the path variable is not updated.

echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin

when I give terraform --version outside the shell script it is not working fine.

But when I give su - , and then try terraform --version it is actually working fine.

Is there any work around for it or automated script for it to the update the .bash_profile. I don't want to restart my session every time I update the .bash_profile?

mblakele
  • 7,782
  • 27
  • 45
sriramsm04
  • 343
  • 1
  • 7
  • 22
  • Are you saying that it's not working when you're not root but it is when you are root? Because that's pretty evident by the profile you edited. – ydaetskcoR Aug 05 '16 at 09:39
  • In which environment you start your script? Is it root-only? Not in a cron-job? Do you start it as a regular user? Remember that bei `>>` you always append the export line into the file. – ferdy Aug 05 '16 at 09:45
  • Not working when i'm logged in as a root user only. No it is not a cron job. This script will always be run as a root user only. – sriramsm04 Aug 05 '16 at 09:51
  • Assume that there are no other users logged in the server or we have to create one after running the script only. So it will be ran using root and root only. – sriramsm04 Aug 05 '16 at 09:53

1 Answers1

5

Shell scripts run in a subshell (which you define int the first line as #!/bin/bash), any change in the environment is local to that subshell, so, the sourcing of bash_profile affects only the subshell.

To execute the commands in your current shell, use the source command to run the script in your current shell (http://ss64.com/bash/source.html)

e.g. instead of

$ ./myscript.sh

run:

$ source ./myscript.sh
Oliver
  • 1,360
  • 9
  • 14