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?

2
  • 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. Commented Feb 6, 2023 at 9:02
  • 1
    As an aside, you must quote your variable to prevent globbing and word splitting: [ -z "$VAR" ] and echo "$VAR". Commented Feb 6, 2023 at 9:09

1 Answer 1

2

Use source example.sh or . example.sh

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.