using source in a bash script

1k Views Asked by At

I've installed some of my code that needs Perl 5.010 on a CentOS 5.x server using perlbrew and it needs the two lines

source ~/perl5/perlbrew/etc/bashrc

and

perlbrew switch perl-5.10.1

To be executed in the shell before I have perl 5.010 in my /usr/bin/env, so I tried to create the following executable bash script to minimise these two steps to ./setEnv.sh

#!/bin/bash
echo "**setting environment variables - 'perlbrew switch-off' to exit"
SETSOURCE= `source ~/perl5/perlbrew/etc/bashrc`
echo $SETSOURCE
SETPERL= `perlbrew switch perl-5.10.1`
echo $SETPERL
2

There are 2 best solutions below

1
On

Use the source command without backticks. Just write a line

source ~/perl5/perlbrew/etc/bashrc

in your script. (source has side-effects, which doesn't work when you are in a sub-shell. I'm not even sure you can run source as an external command.)

2
On

A process can't modify its parent environment, so you are doing it wrong since the shebang.

Doing a source in a backtick (subshell) only affects the subshell, and it ends after the command execution.

    $ ### test.sh assign "inside" to TEST
    $ TEST='outside'; echo "$(source test.sh; echo $TEST)" - $TEST
    inside - outside

What you probably want to do is source your setEnv.sh script directly from your shell.

    $ ### test.sh assign "inside" to TEST
    $ TEST='outside'; source test.sh; echo $TEST 
    inside