[ale] Tinkering with Bash arrays.

Alex Carver agcarver+ale at acarver.net
Sun Jun 25 22:03:15 EDT 2017


First problem, you have to declare "list" as an array.  Readarray won't
create it as a bash array for you, it must already exist as a declared
variable.  Once you do that it should increment properly:

declare -a list
readarray -t list < /tmp/testfile
for l in ${!list[@]}; do echo $l ; done
0
1
2
3
4
5
6
7
8
9
10
...



On 2017-06-25 18:45, askabt wrote:
> Trying to write a script in Bash to generate an ssh config file from a
> list. The list will grow and shrink and the script will regenerate ssh's
> config file.
> 
> I know there is a better way to do this and probably this isn't the best
> approach.  But still was trying to do it with bash, just to figure it
> out if it can be done. Maybe someone knows where I need to look to
> figure it out, or maybe it's not possible. I'm fine either way.
> 
> This script builds several arrays from one array(file) to call them
> later in a loop. Will have to create a ./ssh_config file with variables
> to run script. Or generate your own arrays, I kept it short.
> 
> build_config () ; Works in theory but doesn't increment.
> 
> build_fail () ; Well it fails.
> 
> Running the build_fail Function will error out with
> 
> script: line 48: Host ${aaray$[f][0]}: bad substitution
> 
> or
> 
> script: line 48: Host ${aaray$f[0]}: bad substitution
> 
> 
> #!/bin/bash
> 
> # Example file format for the ./ssh_config file, remove hash in file:
> #{Host} {Hostname}
> #bastion b.server.com
> #mail mail.server.com
> #mail2 mail2.server.com
> #dns dns.server.com
> 
> # Establish Variables:
> IFS=' '
> readarray -t list < ./ssh_config
> 
> 
> # Builds a set of arrays in loop $aaray{1..?}
> # Loop to create individual aarays, range 1 through ${!list[@]}
> for i in ${!list[@]}
>    do
> 
>      declare -a aaray${i}
>      declare "aaray${i}=( ${list[${i}]} )"
> 
> done
> 
> 
> #
> # Loop to build config file. Works but does not increment.
> #
> build_config () {
> 
> for i in ${!list[@]}; do
> 
> echo "Host ${aaray1[0]}"
> echo "    Hostname ${aaray1[1]}"
> echo
> 
> done
> }
> 
> #
> # Loop to increment $aaray[number] by on on each pass. Fails.
> #
> build_fail ()
> {
> 
> for f in ${!list[@]}; do
> 
> echo "Host ${aaray$[f][0]}"
> echo "    Hostname ${aaray$[f][1]}"
> echo
> 
> done
> }
> 
> # Toggle functions for testing
> 
> #build_config
> build_fail
> 
> ### EOF ###
> 
> _______________________________________________
> Ale mailing list
> Ale at ale.org
> http://mail.ale.org/mailman/listinfo/ale
> See JOBS, ANNOUNCE and SCHOOLS lists at
> http://mail.ale.org/mailman/listinfo
> 



More information about the Ale mailing list