Search code examples
linuxshellredhat

Exporting a Path Variable inside a shell script


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?


Solution

  • 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