Is it possible to create an array of objects in bash?
That\'s how I\'m trying:
declare -a identifications=(
{
email = \'...\',
password
You could do some trickery with associative arrays (introduced in Bash 4.0) and namerefs (see manual for declare and the first paragraph of Shell Parameters – introduced in Bash 4.3):
#!/bin/bash
declare -A identification0=(
[email]='test@abc.com'
[password]='admin123'
)
declare -A identification1=(
[email]='test@xyz.org'
[password]='passwd1!'
)
declare -n identification
for identification in ${!identification@}; do
echo "Email: ${identification[email]}"
echo "Password: ${identification[password]}"
done
This prints
Email: test@abc.com
Password: admin123
Email: test@xyz.org
Password: passwd1!
declare -A
declares an associative array.
The trick is to assign all your "objects" (associative arrays) variable names starting with the same prefix, like identification
. The ${!prefix@}
notation expands to all variable names starting with prefix
:
$ var1=
$ var2=
$ var3=
$ echo ${!var@}
var1 var2 var3
Then, to access the key-value pairs of the associative array, we declare the control variable for the for loop with the nameref attribute:
declare -n identification
so that the loop
for identification in ${!identification@}; do
makes identification
behave as if it were the actual variable from the expansion of ${!identification@}
.
In all likelihood, it'll be easier to do something like the following, though:
emails=('test@abc.com' 'test@xyz.org')
passwords=('admin123' 'passwd1!')
for (( i = 0; i < ${#emails[@]}; ++i )); do
echo "Email: ${emails[i]}"
echo "Password: ${passwords[i]}"
done
I.e., just loop over two arrays containing your information.