简体   繁体   中英

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?

尝试

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

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}

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

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.

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

${arrayname[3]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM