bashshellunixenvironment-variables

Can I export a variable to the environment from a Bash script without sourcing it?


Suppose that I have this script:

export.bash:

#! /usr/bin/env bash
export VAR="HELLO, VARIABLE"

When I execute the script and try to access to the $VAR, I don't get any value!

echo $VAR

Is there a way to access the $VAR by just executing export.bash without sourcing it?


Solution

  • Is there any way to access to the $VAR by just executing export.bash without sourcing it ?

    Quick answer: No.

    But there are several possible workarounds.

    The most obvious one, which you've already mentioned, is to use source or . to execute the script in the context of the calling shell:

    $ cat set-vars1.sh 
    export FOO=BAR
    $ . set-vars1.sh 
    $ echo $FOO
    BAR
    

    Another way is to have the script, rather than setting an environment variable, print commands that will set the environment variable:

    $ cat set-vars2.sh
    #!/bin/bash
    echo export FOO=BAR
    $ eval "$(./set-vars2.sh)"
    $ echo "$FOO"
    BAR
    

    A third approach is to have a script that sets your environment variable(s) internally and then invokes a specified command with that environment:

    $ cat set-vars3.sh
    #!/bin/bash
    export FOO=BAR
    exec "$@"
    $ ./set-vars3.sh printenv | grep FOO
    FOO=BAR
    

    This last approach can be quite useful, though it's inconvenient for interactive use since it doesn't give you the settings in your current shell (with all the other settings and history you've built up).