Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

export doesn't work in shell script but does via CLI

I have the following file - test.sh - in .:

#!/bin/sh
export ASDF=test

I do chmod +x test.sh,then ./test.sh and finally echo $ASDF and... nothing. It's as though $ASDF hasn't been set. But if I do it via the CLI instead of a shell script it works just fine and $ASDF is defined.

Why isn't the shell script working?

like image 512
neubert Avatar asked Mar 16 '26 15:03

neubert


1 Answers

It is because:

./test.sh

will create a sub shell and set env variables in the sub shell. Once sub shell exits this variable isn't available in parent shell.

Use this form to avoid forking a sub shell and execute test.sh in the current shell itself:

. ./test.sh

OR:

source ./test.sh

Now that variable ASDF will be available in current shell also.

like image 80
anubhava Avatar answered Mar 19 '26 09:03

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!