LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Problem with bash script - variable name within variable name (https://www.linuxquestions.org/questions/linux-newbie-8/problem-with-bash-script-variable-name-within-variable-name-710320/)

steven.c.banks 03-09-2009 02:53 PM

Problem with bash script - variable name within variable name
 
I need to set and then increment a counter in a bash script, where the counter name contains a variable name.

Here is the relevant part of my script

func_count_fmfm () {
echo "Starting FMFM counts for ${category}"
fmfm_umbillingnumber_count_${category}=0

echo ${fmfm_umbillingnumber_count_${category}}
...
}

##################################################################################
# Main routine

...
category="biz"
func_count_fmfm

category="res"
func_count_fmfm
...

The results:
Starting FMFM counts for biz
Starting FMFM counts for res

line 39: fmfm_umbillingnumber_count_biz=0: command not found
line 40: ${fmfm_umbillingnumber_count_${category}}: bad substitution
line 39: fmfm_umbillingnumber_count_res=0: command not found
line 40: ${fmfm_umbillingnumber_count_${category}}: bad substitution

How do I correctly handle a case like this, of a variable name within a variable name?

Thanks in advance...

openSauce 03-09-2009 04:32 PM

I don't think that's possible in any programming language. It sounds like you want an array - take a look here or on the bash manpage.

colucix 03-09-2009 04:45 PM

You can do that by means of "indirect variable reference". Use the notation ${!variable} introduced in Bash version 2:
Code:

#!/bin/bash
func_count_fmfm () {
echo "Starting FMFM counts for ${category}"
eval "fmfm_umbillingnumber_count_${!category}=0"
echo $fmfm_umbillingnumber_count_${!category}
}

category="biz"
func_count_fmfm
category="res"
func_count_fmfm

The eval is mandatory to let the shell do the correct substitution.

steven.c.banks 03-10-2009 03:08 AM

Problem with bash script - variable name within variable name
 
The second post - to use indirect variable reference - worked perfectly! Many thanks...


All times are GMT -5. The time now is 09:23 AM.