0

How can I use the value of one variable as the name of another variable in an alternative value expansion (${var+alt}) in bash?

I would think that

#!/bin/bash
cat='dog'
varname='cat'
if [ -z ${`echo "${varname}"`+x} ]; then
    echo 'is null'
fi

should be roughly equivalent to

#!/bin/bash
if [ -z ${dog+x} ]; then
    echo 'is null'
fi

but when I try to do this, I get

${`echo "${cat}"`+x}: bad substitution

I guess part of the problem is that the subshell doing the command substitution doesn't know about $varname anymore? Do I need to export that variable?

My reason for doing this is that I learned from this answer how to check if a variable is null, and I'm trying to encapsulate that check in a function called is_null, like this:

function is_null {
    if [ $# != 1 ]; then
        echo "Error: is_null takes one argument"
        exit
    fi
    # note: ${1+x} will be null if $1 is null, but "x" if $1 is not null
    if [ -z ${`echo "${1}"`+x} ]; then
        return 0
    else
        return 1
    fi
}

if is_null 'some_flag'; then
    echo 'Missing some_flag'
    echo $usage
    exit
fi
Community
  • 1
  • 1
Chris Middleton
  • 5,654
  • 5
  • 31
  • 68
  • 2
    I think you need this http://stackoverflow.com/questions/26337826/in-linux-shell-script-how-can-i-recall-value-of-variable/26337979#26337979 – Ashwani Feb 04 '15 at 04:55
  • @Ashwani Thank you, that's just what I needed. I changed my if statement to `if [ -z ${!1+x} ]; then ...` – Chris Middleton Feb 04 '15 at 05:09

1 Answers1

-1

I'm not sure if I understand your problem.

If I got, what you need is eval command.

$ cat='dog'

$ varname='cat'

$ echo ${varname}

cat

$ eval echo \$${varname}

dog
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
Davison
  • 71
  • 3
  • What he was looking for was **indirection**, while that can be accomplished with `eval`, the use of `eval` is frowned upon in such circumstances. – David C. Rankin Apr 11 '15 at 21:29
  • @Davison I appreciate your answer - `eval` can do the job, but as David said, I was trying to avoid the use of that sledgehammer in favor of a more precise tool. I forgot to mark my question as duplicate to the link posted above. – Chris Middleton Apr 11 '15 at 22:32