0

I'm trying to have a bash script create a variable and have the variable persist in the terminal until the terminal closes (not permanently). I thought export was what I needed but it didn't work.

#!/bin/bash

export VARIABLE='this is a test'

Then run the script:

$ ./test.sh

Then in the same terminal:

$ echo "$VARIABLE"

But it produces a blank response.

1
  • A note on executable shell script names: Don't end file name with .sh: User should not need to know the language, and the language can change. Commented Dec 24, 2018 at 11:15

3 Answers 3

1

What happened

You start a new process, set and environment variable (in the process), and exit the process. The variable is gone.

What to do

Source the bash script, don't execute it. e.g. one of these

source ./test.sh 
. ./test.sh
0

When you run the script you create subshell where the variable is set. After end of the script execution the variable is destroyed. If you want to have it in current shell execute the script on this way:

. ./test.sh
0
0

In addition to the source (or .), you might need to use a shell function instead.

Give a try to this:

test_sh() {
  export VARIABLE='this is a test'
  ...
}

Test:

printf "VARIABLE=%s\n" "${VARIABLE}"
VARIABLE=

.

test_sh
printf "VARIABLE=%s\n" "${VARIABLE}
VARIABLE=this is a test

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.