0

I have a shell script setmyenv.sh as below

#!/bin/sh
export PATH=./abc/tools:$PATH
env | grep PATH

When I run it sh setmyenv.sh, I could see that the PATH env is set accordingly.

PATH=./abc/tools:<whatever my existing PATH setting>

However, after my command finish, if I manually type env | grep PATH on the console, I got

PATH=<whatever my existing PATH setting>

I lost the setting that I set using setmyenv.sh It looks like the environement is only set in the lifetime of my script run.

How could I have the environment set sticky even after the script ended. i.e. the purpose of the script is to set the environment.?

P/S: I don't want to set it in my .bash_profile nor etc\profile, given I only want to set it when needed, by calling setmyenv.sh, but not every time I open my console. i.e. not per the answer of Using .sh script to set an environment variable or How to set global environment variables using shell script .sh

1 Answer 1

4

When you run

sh setmyenv.sh

it runs in a separate sh process and the changes to PATH are lost when the process finishes.

You need to source your script:

source setmyenv.sh

or

. setmyenv.sh

so that it runs in your current shell and all variable assignments are preserved. Remember not to have any exit in setmyenv.sh script. If you do, sourcing the script will terminate your shell.


See also:

Sign up to request clarification or add additional context in comments.

1 Comment

When you run sh setmyenv.sh it runs in a separate shell process - which is not the same as a subshell. A subshell has specific properties, for example local variables can be read in a subshell - they don't have to be exported. Usually subshells are created using parentheses, for example ( commands ).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.