1

I will be reading variables in from a config file. Say, for instance, that the file looks like this:

cfg1=hello
cfg2=there

My script will read that in, so it will have variables names $cfg1 and $cfg2. I now want to determine if the command line argument matches one of the defined variables. I.e., if I execute script.sh cfg1 I want my if statement to pass, but if I execute script.sh cfg3 it should fail.

I'm aware of the \$$varname syntax, but frankly I can't figure out how it works. I've tried:

if [[ \$$1 ]]

but that's always passes.

2 Answers 2

5

You can use parameter expansion:

#!/bin/bash

cfg1=hello
cfg2=''

for varname in cfg{1..3} ; do
    echo $varname
    if [[ ${!varname+1} ]] ; then
        echo ok
    fi
done
  • +1 replaces the value with 1 if the variable is defined.
  • ! introduces variable indirection, i.e. the variable $varname is used as the variable's name.
Sign up to request clarification or add additional context in comments.

Comments

3

Use the -v test in bash 4.2 or later:

if [[ -v $1 ]]; then
    echo "Variable $1 is defined"
else
    echo "Variable $1 is not defined"
fi

@choroba's answer should work in any earlier version one is likely to be using.

1 Comment

Good to know about -v. Just to avoid potential confusion: -v $1 works perfectly here, because the value of $1 is the name of the variable whose existence to test. By contrast, you can use neither -v $1 nor -v 1 to test if $1 itself was passed or not (examine $# for that).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.