Reputation: 588
I have the following bash script. It is actually an env variable file that contains some environment variables I want to set depending on an argument I pass in when I source it. Here is a MWE.
#!/usr/bin/env bash
# CONSTANTS
PROD_STR='prod'
TEST_STR='test'
# Set the environment: 'prod' or 'test'
if [ "$1" == $PROD_STR ] || [ "$1" == $TEST_STR ]; then
export DEV_ENV=$1
echo "Found valid dev environment: "$DEV_ENV
else
echo "No valid environment specified"
echo "Usage: env_vars <env>"
echo ' env - one of "prod" or "test"'
fi
case $DEV_ENV in
$PROD_STR)
export MY_HOST='fooProd.net'
export PORT='8000';;
$TEST_STR)
export MY_HOST='fooTest.net'
export PORT='8100';;
esac
export API_USERNAME='foo'
export API_PASSWORD='mypwrd'
Now I wanted to source
this file which I have named test_env_var.sh
. I tried.
source test_env_var.sh prod
It gives me the following test_env_var.sh:8: = not found
. ./test_env_var.sh prod
.
It still gives me: ./test_env_var:8: = not found
.
./test_env_var prod
It now runs without errors and echoes (as it should) the output
Found valid dev environment: prod
.
So now after doing (3) I would expect to see my env variables set. But when I do
echo $API_USERNAME
It doesn't return anything.
Workaround
I temporarily change my $SHELL into bash by typing bash
on the prompt. Then I run the script as
. test_env_var prod
and now when I try to echo
any env variable
I have set (for example echo $API_USERNAME
it returns me foo
as it should ). Even if I change back to zsh
by typing zsh
the environment variables are still there.
Question:
Why is this happening?. Is there no way for me to run this bash script without changing the $SHELL to bash?. Perhaps the syntax of the bash script needs to change so that it runs on zsh
. But that's not an option since this file is under version control.
Some more context
Both my zsh
and bash
are usr/local/bin/
so the shebang #!/usr/bin/env bash
should take care of this, I would think.
Upvotes: 3
Views: 4249
Reputation: 64
To answer your confusion regarding
Even if I change back to zsh by typing zsh the environment variables are still there.
You're essentially nesting shell sessions inside each other, so if you execute exit
twice, you go back to your initial shell.
ex:
zsh> bash
bash> zsh
zsh>
zsh> exit
bash> exit
zsh>
Upvotes: 0
Reputation: 782624
Change
if [ "$1" == $PROD_STR ] || [ "$1" == $TEST_STR ]; then
to
if [ "$1" = $PROD_STR ] || [ "$1" = $TEST_STR ]; then
==
is a bash
extension. =
is the standard POSIX syntax, which is supported by both bash
and zsh
.
Upvotes: 3