0

I wrote a bash script to set the environment variable VAR if it is currently not set:

example.sh

#!/bin/bash

if [ -z $VAR ]; then
    export VAR=abc
fi

Now I type this in the command line: ./example.sh && echo $VAR. I expect abc, but the result is blank. Why?

user3100212
  • 101
  • 1
  • 5
  • 2
    You must run it as `source ./example.sh && echo $VAR`. Your command sets the environment variable within the context of `example.sh` script (which runs in a subshell): this cannot affect the parent environment. – M. Nejat Aydin Feb 06 '23 at 09:02
  • 1
    As an aside, you must quote your variable to prevent globbing and word splitting: `[ -z "$VAR" ]` and `echo "$VAR"`. – M. Nejat Aydin Feb 06 '23 at 09:09

1 Answers1

1

Use source example.sh or . example.sh

akathimi
  • 1,393
  • 11