Pranesh Prakash
Pranesh Prakash

Reputation: 3

Declare a variable using an array variable substitution before the for loop

I'm trying to include a reference to a variable (B) in another variable (A). B gets its value from an array during a for loop, and I would hope for A to also get the same value, but that does not work.

#!/bin/bash
A=$B

ARRAY=( 1 2 3 )

for B in ${ARRAY[@]}
  do
  echo "A="$A
  echo "B="$B
done

How do i get $A to have the same value as $B?

Upvotes: 0

Views: 46

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84561

With bash >=4 you can accomplish what you want using a nameref. A nameref is created using declare or local with the -n option. To create A as a nameref of B, you would use:

declare -n A=B      ## declare A as a 'nameref' of B

Then using your script:

#!/bin/bash

declare -n A=B      ## declare A as a 'nameref' of B

ARRAY=( 1 2 3 )

for B in ${ARRAY[@]}
do
    echo "A="$A
    echo "B="$B
done

Example Use/Output

$ bash namerefAB.sh
A=1
B=1
A=2
B=2
A=3
B=3

Upvotes: 2

jmp
jmp

Reputation: 2375

Not sure if this answers your question the way you want but I believe A just need to be assigned in the for loop and not the beginning of the script as B doesn't have a value then.

#!/bin/bash
A=$B
# B is not assigned there which is why A is ""
echo "B: $B"
ARRAY=( 1 2 3 )

for B in ${ARRAY[@]}
  do
  # B is assigned here so A is assigned the same value
  A=$B
  echo "A="$A
  echo "B="$B
done

OUTPUT:

B:
A=1
B=1
A=2
B=2
A=3
B=3

Upvotes: 0

Related Questions