How to check if a variable exists and whether it has been initialized

I need to execute a function that should check if a variable is correctly defined in bash and should use its associated value.

For example, these variables are initialized at the top of the script.

#!/bin/bash var1_ID=0x04 var2_ID=0x05 var3_ID=0x06 var4_ID=0x09 

I would call the script named tag like this:

 ./test var1 

Current implemented function:

 function Get() { if [ $1"_ID" != "" ]; then echo "here" echo $(($1_ID)) else exit 0 fi } 

I don’t understand why I get here even if I ./test toto or something else.

Do I need to use a specific command, for example grep ?

+5
source share
3 answers

You probably want to use the indirect extension: ${!variable} and then -n to check if it has been defined:

indirect extension consists in calling a variable with another variable. That is, since the variable name can change, instead of the expression $a we say ${!var} and var=a .

 $ cat a var1_ID=0x04 var2_ID=0x05 var3_ID=0x06 var4_ID=0x09 for i in {1..5}; do v="var${i}_ID" if [ -n "${!v}" ]; then # <-- this expands to varX_ID echo "$v set to value: ${!v}" else echo "$v not set" fi done 

If we do, we get:

 $ ./a var1_ID set to value: 0x04 var2_ID set to value: 0x05 var3_ID set to value: 0x06 var4_ID set to value: 0x09 var5_ID not set 

From man test :

-n STRING

length STRING is not zero

+8
source

Use parameter extension:

 : ${var:?} 

Remove the colon if the empty string is a valid value (i.e. you only want to check for certainty).

 : ${var?} 

If you do not want the script to dwell on the problem, you can use

 if [[ ${var:+1} ]] ; then # OK... else echo Variable empty or not defined. >&2 fi 
+5
source

In bash 4.2, you can use the -v operator in a conditional expression to check if a variable with the given name is set.

 if [[ -v ${1}_ID ]]; then echo "${1}_ID is set" foo=${1}_ID echo "${!foo}" fi 

Obtaining a value still requires an indirect extension of the parameter.

In bash 4.3, you can use a named link to make it easier to use.

 declare -n param=${1}_ID if [[ -v param ]]; then echo "${1}_ID" echo "$param" fi 

( param will behave exactly like the variable it refers to. I don't know if there is a simple way that does not parse the output of declare -p param to get the name of the variable it refers to.)

+3
source

Source: https://habr.com/ru/post/1207601/


All Articles