[bash] 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 get no value!

echo $VAR

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

This question is related to bash shell unix environment-variables

The answer is


I don't think this can be done but I found a workaround using alias. It will only work when you place your script in your scripts directory, otherwise your alias will have an invalid name. The only point to the work around is to be able to have a function inside a file with the same name and not have to bother sourcing it before using it. Add the following code to ~/.bashrc:

alias myFunction='unalias myFunction && . myFunction && myFunction "$@"'

You can now call myFunction without sourcing it first.


The answer is no, but for me I did the following

the script: myExport

#! \bin\bash
export $1

an alias in my .bashrc

alias myExport='source myExport' 

Still you source it, but maybe in this way it is more useable and it is interesting for someone else.


Maybe you can write a function in ~/.zshrc, ~/.bashrc .

# set my env
[ -s ~/.env ] && export MYENV=`cat ~/.env`
function myenv() { [[ -s ~/.env ]] && echo $argv > ~/.env && export MYENV=$argv }

Beacause of use variable outside, you can avoid write script file.


Execute

set -o allexport

Any variables you source from a file after this will be exported in your shell.

source conf-file

When you're done execute. This will disable allexport mode.

set +o allexport

Another workaround that, depends on the case, it could be useful: creating another bash that inherites the exported variable. It is a particular case of @Keith Thompson answer, will all of those drawbacks.

export.bash:

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

Now:

./export.bash
echo $VAR

In order to export out the VAR variable first the most logical and seems working way is to source the variable:

. ./export.bash

or

source ./export.bash

Now when echoing from main shell it works

 echo $VAR
HELLO, VARABLE

We will now reset VAR

export VAR=""
echo $VAR

Now we will execute a script to source the variable then unset it :

./test-export.sh 
HELLO, VARABLE
--
.

the code: cat test-export.sh

    #!/bin/bash
    # Source env variable
    source ./export.bash

    # echo out the variable in test script
    echo $VAR

    # unset the variable 
    unset VAR
    # echo a few dotted lines
    echo "---"
    # now return VAR which is blank
    echo $VAR

Here is one way

PLEASE NOTE: The exports are limited to the script that execute the exports in your main console - so as far as a cron job I would add it like the console like below... for the command part still questionable: here is how you would run in from your shell:

On your command prompt (so long as the export.bash has multiple echo values)

IFS=$'\n'; for entries in $(./export.bash); do  export $entries;  done; ./v1.sh 
HELLO THERE
HI THERE

cat v1.sh

#!/bin/bash
echo $VAR
echo $VAR1

Now so long as this is for your usage - you could make the variables available for your scripts at any time by doing a bash alias like this:

myvars ./v1.sh
HELLO THERE
HI THERE

echo $VAR

.

add this to your .bashrc

function myvars() { 
    IFS=$'\n'; 
    for entries in $(./export.bash); do  export $entries;  done; 

    "$@"; 

    for entries in $(./export.bash); do variable=$(echo $entries|awk -F"=" '{print $1}'); unset $variable;
done

}

source your bashrc file and you can do like above any time ...

Anyhow back to the rest of it..

This has made it available globally then executed the script..

simply echo it out then run export on the echo !

cat export.bash

#!/bin/bash
echo "VAR=HELLO THERE"

Now within script or your console run:

 export "$(./export.bash)"

Try:

echo $VAR
HELLO THERE

Multiple values so long as you know what you are expecting in another script using above method:

cat export.bash

#!/bin/bash
echo "VAR=HELLO THERE"
echo "VAR1=HI THERE"

cat test-export.sh

#!/bin/bash

IFS=$'\n'
for entries in $(./export.bash); do
   export $entries
done

echo "round 1"
echo $VAR
echo $VAR1

for entries in $(./export.bash); do
     variable=$(echo $entries|awk -F"=" '{print $1}');
     unset $variable
done

echo "round 2"
echo $VAR
echo $VAR1

Now the results

 ./test-export.sh 
round 1
HELLO THERE
HI THERE
round 2


.

and the final final update to auto assign read the VARIABLES:

./test-export.sh 
Round 0 - Export out then find variable name - 
Set current variable to the variable exported then echo its value
$VAR has value of HELLO THERE
$VAR1 has value of HI THERE
round 1 - we know what was exported and we will echo out known variables
HELLO THERE
HI THERE
Round 2 - We will just return the variable names and unset them 
round 3 - Now we get nothing back

The script: cat test-export.sh

#!/bin/bash

IFS=$'\n'
echo "Round 0 - Export out then find variable name - "
echo "Set current variable to the variable exported then echo its value"
for entries in $(./export.bash); do
 variable=$(echo $entries|awk -F"=" '{print $1}');
 export $entries
 eval current_variable=\$$variable
 echo "\$$variable has value of $current_variable"
done


echo "round 1 - we know what was exported and we will echo out known variables"
echo $VAR
echo $VAR1

echo "Round 2 - We will just return the variable names and unset them "
for entries in $(./export.bash); do
 variable=$(echo $entries|awk -F"=" '{print $1}');
 unset $variable
done

echo "round 3 - Now we get nothing back"
echo $VAR
echo $VAR1

Found an interesting and neat way to export environment variables from a file:

in env.vars:

foo=test

test script:

eval `cat env.vars`
echo $foo         # => test
sh -c 'echo $foo' # => 

export eval `cat env.vars`
echo $foo         # => test
sh -c 'echo $foo' # => test

# a better one. "--" stops processing options, 
# key=value list given as params
export -- `cat env.vars`
echo $foo         # => test
sh -c 'echo $foo' # => test

Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to unix

Docker CE on RHEL - Requires: container-selinux >= 2.9 What does `set -x` do? How to find files modified in last x minutes (find -mmin does not work as expected) sudo: npm: command not found How to sort a file in-place How to read a .properties file which contains keys that have a period character using Shell script gpg decryption fails with no secret key error Loop through a comma-separated shell variable Best way to find os name and version in Unix/Linux platform Resource u'tokenizers/punkt/english.pickle' not found

Examples related to environment-variables

Using Environment Variables with Vue.js Adding an .env file to React Project Is there any way to set environment variables in Visual Studio Code? Test process.env with Jest How to set environment variables in PyCharm? ARG or ENV, which one to use in this case? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? What is a good practice to check if an environmental variable exists or not? Passing bash variable to jq Tensorflow set CUDA_VISIBLE_DEVICES within jupyter