1

I am currently working on a script that receives the input string and then use it as the defined array name. But I stuck with this, thanks in advance

a=(1 2 3)
b=(4 5 6)
c=(7 8 9)

if input from user is "a", I want the result_array will be like (1 2 3)?

a=(1 2 3); b=(4 5 6); input="a"; result_array=("${${input}[@]}"); echo ${result_array[@]}

bash: ${${input}[@]}: bad substitution

All I want is: result_array=("${${input}[@]}") => result_array=("${a[@]}") = (1 2 3)

Note: I dont want to use IF statements like "if input = a or b or c, result_array= a or b or c", because I have to do this step many times.

3 Answers 3

1
a=(1 2 3); 
b=(4 5 6);
# ...
input="a"; # get the user input
result_array=${input}[@];
echo \(${!result_array}\)

will print:

(1 2 3)
Sign up to request clarification or add additional context in comments.

1 Comment

great! that's what I need. Thank you
1

Case is more simple than IF in this case. Also faster.

#!/bin/bash

case "$1" in
    a) result_array=(1 2 3);;
    b) result_array=(4 5 6);;
    c) result_array=(7 8 9);;
esac

echo ${result_array[@]}

I also made a script calculate the array according to char ascii positions compered to a, since you said you don't like to use IF.

#!/bin/bash

# a ascii value
a_num=$(echo a|od -t d1 | awk '{printf "%s" ,$2}')

# input ascii value
ascii=$(echo $1|od -t d1 | awk '{printf "%s" ,$2}')

multiplier=$((($ascii - $a_num) * 3))

result_array=( $((1 + $multiplier)) $((2 + $multiplier)) $((3 + $multiplier)))

echo ${result_array[@]}

Ouputs:

./ascii.sh a
1 2 3
./ascii.sh b
4 5 6
./ascii.sh c
7 8 9
./ascii.sh w
67 68 69
./ascii.sh x
70 71 72

1 Comment

although it is not what I want at the beginning, I like your idea (using "case" to handle this situation). Thanks alot
0

there are 2 ways to do this. Starting from

a=(1 2 3)
b=(4 5 6)
# ...
input="a"
  1. use a nameref (bash v4.4)

    declare -n input                 # set the "nameref" attribute for the variable
    result_array=( "${input[@]}")
    printf "%s\n" "${result_array[@]}"
    
    1
    2
    3
    

    To "reuse" the input variable to point to b, input=b is insufficient. That sets input[0] (and hence a[0]) to "b". You need use declare -n input=b

  2. use indirect expansion (as @tso did in his answer)

    tmp="${input}[@]"           # a string that looks like array expansion
    result_array=( "${!tmp}" )
    printf "%s\n" "${result_array[@]}"
    
    1
    2
    3
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.