-1

EDIT2: @glenn jackman I thought this would fix it, but it still errs in my full script. Why isn't it working? Is it due to the indirect reference?

#!/home/$current_user/Desktop/expect
...
    COUNTER=0
         while [  $COUNTER -lt $num ]; do
             let index=COUNTER+1
             tmp=user_$index
             echo "Changing Password for " ${!tmp}
             echo ${!tmp}
             sudo passwd ${!tmp}
             expect -exact "[sudo] password for $current_user: "
             send "$pass\r"
             interact
             expect -exact "New password: "
             send "$password\r"
             interact
             let COUNTER=COUNTER+1 
         done

EDIT: The ! or the /$$ works for calling just variables inside of other variables. I need help for a case where the variable is part of a string.

I had a quick question regarding indirect variable references in Bash.

eval "\${user_$index\}"  #First attempt
echo \$${eval "{user_\$index}"} #Second attempt

Basically I have several variables named "user_num" where the num is a integer. Each of these variables contains a String value. I want to call that string value by calling the variable. However, since the variable has a variable inside of it (num), I can't seem to get it working. I've looked through the Man pages for Indirect References in Bash, but they don't mention cases where the variable inside of another variable is attached to a string.

TLDR: My question is how do you do this:

$(var_$num)
codeforester
  • 39,467
  • 16
  • 112
  • 140
LockX
  • 51
  • 2
  • 7

1 Answers1

1

This is really quite awkward in bash: you require a temporary variable to hold the constructed variable name:

$ var_1=hello
$ num=1
$ tmp=var_$num
$ echo ${!tmp}
hello

Arrays are much simpler

$ var=( [1]=world )
$ echo ${var[$num]}
world
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Could you help me figure out why the expect portion in the whole script isn't working? I thought this would fix it. – LockX Sep 05 '15 at 23:00
  • Shell and expect are different languages, so you can't mix them up like that. Your shebang line is expect: use expect control structures, conditionals and arithmetic. – glenn jackman Sep 06 '15 at 07:00