dnc
dnc

Reputation: 620

Bash, variables and arrays

I crawled through lots of boards but didn't find the final solution for my problem.

I have got an array, named "array0", the name is stored to a variable called arrayname. Also I've got a logged IP address, let's say 127.0.0.1, also stored in a variable, called ip.

Now I want to assign the IP to index 3 in the array like that:

"$arrayname"[3]="$ip"    

So, this didn't work. I tried lots of ways how to solve that but none worked.
Is anyone out there who can tell me the final solution for this case?

Update: The given opportunities to handle the problem are great! But I forgot to mention that the array I'm working with is just sourced from another file (also written in bash). My goal is now to edit the array in the sourced file itself. Any more ideas for that?

Upvotes: 1

Views: 147

Answers (5)

PM 2Ring
PM 2Ring

Reputation: 55499

And yet another way to do it, this time using the versatile printf.

printf -v "$arrayname[3]" %s "$ip"

demo

#!/bin/bash

array0=(a b c d e)
echo "${array0[@]}"

arrayname='array0'
ip='127.0.0.1'

printf -v "$arrayname[3]" %s "$ip"
echo "${array0[@]}"

output

a b c d e
a b c 127.0.0.1 e

Upvotes: 2

chepner
chepner

Reputation: 532303

You'll need to use the declare command and indirect parameter expansion, but it's a little tricky to use with array names. It helps if you think of the index as part of the variable name, instead of an operator applied to the array name, like in most languages.

array0=(1 2 3 4 5)
arrayname=array0
name=$arrayname[3]
declare "$name=$ip"
echo "${!name}

Upvotes: 2

SMA
SMA

Reputation: 37093

See this:

# declare -a arrayname=(element1 element2 element3)
# echo ${arrayname[0]}
  element1
# arrayname[4]="Yellow"
# echo ${arrayname[4]}
  Yellow
# export ip="192.168.190.23"
# arrayname[5]=$ip
# echo ${arrayname[5]}
  192.168.190.23

You don't have to use quotes.

Upvotes: 0

Jdamian
Jdamian

Reputation: 3125

Try

read ${arrayname}[3] <<<"$ip"

Upvotes: 5

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7128

After initializing the arrays, you can access the array elements using their indices as follows. Access as:

${arrayname[3]}

Upvotes: -1

Related Questions