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.

marked as duplicate by Jeff Schaller, A.B, mosvy, Stephen Harris, thrig Dec 24 '18 at 19:54

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 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. – ctrl-alt-delor Dec 24 '18 at 11:15
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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.