1

I am setting an environment variable in my terminal with no value.

setenv ABC

Now I want to check in my bash script if this variable is set or not.

#!/bin/bash        

ABC_USAGE=0

if [[ -z "$ABC" ]] ;  then
  ABC_USAGE=$((ABC_USAGE+1))
fi
 echo $ABC_USAGE

I want to increase $ABC_USUAGE value only if $ABC is set in terminal without any value. My code is increasing this value anyway. which is not expected result. please help..

5
  • even if you use just set to set the variable, as far as I know -z only checks if it is empty Commented Aug 10, 2018 at 10:31
  • I am setting it in my terminal outside the script. and want to check inside the script. This variable has not value. Commented Aug 10, 2018 at 10:31
  • 1
    then the if statement will always be true as the variable is empty even if it is set Commented Aug 10, 2018 at 10:32
  • 1
    yes , thats what the problem I'm facing .. Could you please help me with correct syntax ?? Commented Aug 10, 2018 at 10:36
  • kindly look at the answer for explanation Commented Aug 10, 2018 at 10:48

1 Answer 1

4

use this instead of the if expression that you are using

if [ -z ${ABC+x} ]

this will evaluate to be nothing if the variable isn't set and if the variable will be set the condition will be true.

This expression:

if [[ -z "$ABC" ]]

only checks if the variable has any value assigned or if the variable is empty

it will always be true if you just set the variable and the variable has no value assigned to it.

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.