[ale] Tinkering with Bash arrays.
askabt
askabt at gmail.com
Sun Jun 25 21:45:40 EDT 2017
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 ###
More information about the Ale
mailing list