0

I have a doubt. When i declare a value and assign to some variable, I don't know how to reassign the same value to another variable. See the code snippet below.

Here is my actual script.

#!/bin/sh

a=AA
b=BB
c=CC
d=DD
e=EE
f=FF

alpha_array=(a b c d e f)
process_array=(proc1 proc2 proc3 proc4)
array_1=("")
array_2=("")

display_array() {
echo "array1 = ${array_1[@]}"
echo "array2 = ${array_2[@]}"
}

checkarg() {
if [[ " ${alpha_array[*]} " == *" $token "* ]]; then
    echo "alphabet contains $token "
    array_1=("${array_1[@]}" "$token")
    $token=${$token}
    echo "TOKEN = $token"
elif [[ " ${process_array[*]} " == *" $token "* ]]; then
    echo "process contains $token "
    array_2=("${array_2[@]}" "$token")
else
echo "no matches found"
display_array
exit 1
fi
}

for token in $@
do
   echo $token
   checkarg
done

display_array

Here the below two lines

$token=${$token}
echo "TOKEN = $token"

should display my output as

TOKEN = AA
TOKEN = BB 

when i run my script with the following arguments.

./build.sh a b proc1

Kindly help me out on those 2 lines.

3
  • What do you want the line $token=${$token} to do? That is, if it operated correctly, what would it accomplish? Commented Dec 19, 2014 at 0:59
  • 1
    By the way, the modern replacement for array_1=("${array_1[@]}" "$token") is array_1+=( "$token" ) -- both shorter to write and faster execution. Commented Dec 19, 2014 at 1:01
  • I need to assign the incoming argument 'a' to token and get the value of $a. Commented Dec 19, 2014 at 1:03

1 Answer 1

2

It sounds like what you want is variable indirection. There's a lot of code in your question which has nothing to do with that, but let me try to distill it down to what I understand as the important parts:

a=AA
b=BB
alpha_array=(a b)
for token in "${alpha_array[@]}"; do
  value=${!token}
  echo "value of variable $token is $value"
done

When run, this will output:

value of variable a is AA
value of variable b is BB

For more details, see BashFAQ #6.


By the way, this can often be replaced with use of associative arrays, in which case you might write:

declare -A tokens=( [a]=AA [b]=BB )
for token in "${!tokens[@]}"; do
  value=${tokens[$token]}
  echo "value of token $token is $value"
done

This has the advantage that your key/value pairs are all stored inside the array -- there's no potential for collision with other variable names.

Sign up to request clarification or add additional context in comments.

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.