5

I want to somehow enter a different bash shell with some altered environment variables.

For example, if I run script bfin.sh and it contains something like

export PATH=/home/me/bfin2012:$PATH

I want it to create a bash shell with this changed variable. How to do this?

4 Answers 4

5

To load environment variables you've put into a file, you can use the source command. e.g.

See current path:

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

File with custom environment settings..

 > cat exports
 export PATH="/home/me/bfin2012:$PATH"
 export ...

Load custom environment

 > source exports

Confirm changes.

 > env | grep '^PATH'
 PATH=/home/me/bin2012:/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin
1

You've already set the variable and exported the set variable. If you want to enter a new bash shell at this point with that variable present, you just run:

bash

Note that the new shell's startup procedure might end up overwriting your variable, though! This could happen in .bashrc, for example.

0

Either change your script to end with exec bash, or run

sh -c '. bfin.sh; exec bash'

If you want to change the environment of the current shell, run

. bfin.sh

The . (dot or period) builtin executes the command from the specified script inside the same shell environment, like a function.

0

Running the bfin.sh script will do little for you. It would change the value of the PATH environment variable and then terminate. The changed variable is part of the script's environment, so it would be lost when the script ends.

The bash shell will automatically source the file mentioned by the BASH_ENV variable before running a script, so assuming that your script myscript has a #!-line referring to the bash interpreter, the following would source the bfin.sh script and then run your script with the modified environment:

BASH_ENV=path/to/bfin.sh ./myscript

You may also source the bfin.sh script from within your new script:

#!/bin/bash

source path/to/bfin.sh

# the rest of the script goes here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .