Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set PATH only in bash script temporarily?

Tags:

bash

PATH can be set temporarily for following commands. Also, PATH can be set in a script, which remains permanently (in that terminal, or session). How can I set PATH that is globally effective in the script but not after the script finishes?

Example:

PATH=$PATH:/path1 path1 is valid only for this line
export PATH=$PATH:/path2
path2 is valid for this line
and this line too
I like it

exit

> path2 is still valid after the script finishes
> and when I type commands here manually
> I don't like it
like image 626
akai Avatar asked Dec 28 '16 08:12

akai


People also ask

How do you put a PATH in a bash script?

For Bash, you simply need to add the line from above, export PATH=$PATH:/place/with/the/file, to the appropriate file that will be read when your shell launches. There are a few different places where you could conceivably set the variable name: potentially in a file called ~/. bash_profile, ~/.

How do I change the PATH of a script?

You yourself might want to change your PATH in your shell profile. But on top of that, the PATH will be different in different contexts. For example, open the Script Editor application, make a new script document, enter do shell script "echo $PATH" and run the script by hitting the run/play button.

How do I change PATH in bash?

To make the change permanent, enter the command PATH=$PATH:/opt/bin into your home directory's . bashrc file. When you do this, you're creating a new PATH variable by appending a directory to the current PATH variable, $PATH .


2 Answers

I think you are looking for "source" command (linux).

First write you set Path command (or whatelse) in file, like this loadMyEnvironment.sh

#!/bin/bash
export PATH="$PATH:test"
export MESSAGE="Now i am available on the current shell"

Now,type in the shell,

> source ./loadMyenvironment.sh

Now, in current shell you can check that your envs are loaded.

> echo $MESSAGE
Now i am available on the current shell

hope this helps.

like image 37
danipenaperez Avatar answered Sep 28 '22 04:09

danipenaperez


it's simply not true. If you write a script and change the $PATH variable, the change live only in the script:

vi test.sh

inside the file:

#!/bin/bash

export PATH="$PATH:test"

let's test:

echo $PATH
/usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/home/matteo/.local/bin:/home/matteo/bin:./bin:/home/matteo/.local/bin:/home/matteo/bin:./bin

chmod ug+x test
./test 
echo $PATH
/usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/home/matteo/.local/bin:/home/matteo/bin:./bin:/home/matteo/.local/bin:/home/matteo/bin:./bin

same output. The change is effective only inside the script!

like image 190
m47730 Avatar answered Sep 28 '22 03:09

m47730