1

I am trying to break up a returned value from a mysql call in a shell script. Essentially what I have done so far is query the database for IP addresses that I have stored in a specific table. From there I store that returned value into a bash variable. The code is below:

#!/bin/bash

# This file will be used to obtain the system details for given ip address

retrieve_details()
{
  # get all the ip addresses in the hosts table to pass to snmp call
  host_ips=$(mysql -u user -ppassword -D honours_project -e "SELECT host_ip FROM hosts" -s)
echo "$host_ips"
  # break up the returned host ip values

  # loop through array of ip addresses
  # while [  ]
  # do

     # pass ip values to snmp command call

     # store details into mysql table host_descriptions

  # done
}

retrieve_details

So this returns the following:

192.168.1.1
192.168.1.100
192.168.1.101

These are essentially the values I have in my hosts table. So what I am trying to do is break up each value such that I can get an array that looks like the following:

arr[0]=192.168.1.1
arr[1]=192.168.1.100
arr[2]=192.168.1.101
...

I have reviewed this link here: bash script - select from database into variable but I don't believe this applies to my situation. Any help would be appreciated

2 Answers 2

1
host_ips=($(mysql -u user -ppassword -D honours_project -e "SELECT host_ip FROM hosts" -s));

outer () will convert that in array. But you need to change your IFS (Internal Field Separator) to a newline first.

IFS=$'\n';
   host_ips=($(mysql -u user -ppassword -D honours_project -e "SELECT host_ip FROM hosts" -s));
unset IFS;
for i in ${host_ips[@]} ; do echo $i ; done;

to print with key

for i in "${!host_ips[@]}"
do
  echo "key :" $i "value:" ${host_ips[$i]}
done
Sign up to request clarification or add additional context in comments.

Comments

0
wspace@lw:~$ echo $host_ips
192.168.1.1 192.168.1.100 192.168.1.101
wspace@lw:~$ arr=($(echo $host_ips))
wspace@lw:~$ echo ${arr[0]}
192.168.1.1
wspace@lw:~$ echo ${arr[1]}
192.168.1.100
wspace@lw:~$ echo ${arr[2]}
192.168.1.101
wspace@lw:~$ echo ${arr[@]}
192.168.1.1 192.168.1.100 192.168.1.101
wspace@lw:~$ 

maybe this is what you want

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.