help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] The best way to derefrence a variable whose name is stor


From: Stephane Chazelas
Subject: Re: [Help-bash] The best way to derefrence a variable whose name is stored in another variable.
Date: Fri, 24 Apr 2015 23:01:55 +0100
User-agent: Mutt/1.5.21 (2010-09-15)

2015-04-24 14:42:26 -0500, Peng Yu:
> Hi I use the following code to test if the variable name stored in "x"
> actually have any value set. But I am not sure if it is the best way
> to do.
> 
> Does anybody know what is the best way to do so in bash?
> 
> #!/usr/bin/env bash
> 
> var=10
> x=var
> 
> if [ "$(eval echo "\$$x")" ]
> then
>   echo "the variable '$x' has a value"
> else
>   echo "the variable '$x' has no value"
> fi
[...]

bash specific:

  if [[ ${!x} ]]; then
    echo "\$$x has a non-null value"
  fi

  if declare -p -- "$x" > /dev/null 2>&1; then
    echo "\$$x is set"
  fi

POSIX:

  if eval '[ "${'"$x"}'" ]'; then
    echo "\$$x has a non-null value"
  fi

  if eval '[ "${'"$x"+.}'" ]'; then
    echo "\$$x is set"
  fi

-- 
Stephane




reply via email to

[Prev in Thread] Current Thread [Next in Thread]