I'm making a function to easly convert my strings to arrays as I need to.
I am somewhat running into a weird issue. I am still new to bash and this is really bugging me. Would anybody be able to shed some light onto this?
convert.sh
#!/bin/bash
convert2array () {
read -a $1_arr <<< $1
}
mx=$(dig +short google.com mx | cut -d' ' -f 2 | sed 's/\.$//')
convert2array "$mx"
echo ${mx_arr[@]}
Output:
bash -x convert2array.sh
++ sed 's/\.$//'
++ cut '-d ' -f 2
++ dig +short google.com mx
+ mx='alt2.aspmx.l.google.com
alt3.aspmx.l.google.com
alt1.aspmx.l.google.com
aspmx.l.google.com
alt4.aspmx.l.google.com'
+ convert2array mx
+ read -a mx_arr
+ echo 585911
585911
You can directly store the
dig
results in the arrayAlso, you need not use
cut
here,sed
alone would suffice.See [ bash arrays ],[ command subsctitution ] and [ positional parameters ].
You're warned : The output can be but in one format. Though
( $( .. ) )
is an anti-pattern as pointed out in comment#1 , for this case, it would suffice.