0

I'm working on a script to check the status of several remote MYSQL hosts by logging into the every server and recording whether the login has been successful or not. The idea is to store the login details for the MYSQL hosts in a CSV file and get the script to loop through this file, login and record if login has been successfull.

The MYSQL Login data stored in the CSV file would the following:

$host,$user,$password

Being a novice at bash scripting, I'm having trouble understanding on how it's best to approach the part where the script loops through a CSV to obtain MYSQL details. Can anyone help?

Currently I tested the below for individual MYSQL Hosts

mysql -h$host -=$user -p$pass -d$db -e exit
if [ "$?" -eq "0" ]
then
        echo "Connection established"
else
        echo "Connection not established"
fi

Thanks in advance.

0

You can use the read builtin and tell it that it should split the line on commas using the IFS (input field separator) shell variable:

$ cat file 
user1,host1,pass1
user2,host2,pass2

$ while IFS="," read -r user host pass; do echo "$user:$host:$pass"; done < file 
user1:host1:pass1
user2:host2:pass2

So, in your script, you would want something like:

while IFS="," read -r user host pass; do 
    if mysql -h "$host" -u "$user" -p"$pass" -e exit; then 
        echo "Connection established"
    else 
        echo "Connection failed" fi; 
done < file

The above, however, will break if any of your passwords (or other variables, but I assume only the passwords might have this issue) contain a comma. If that can be a problem for you, you will have to change the separator to something else instead of a comma. Something that will never appear in a password. For example a tab, and then you can do:

while IFS=$'\t' read -r user host pass; do 
    if mysql -h "$host" -u "$user" -p"$pass" -e exit; then 
        echo "Connection established"
    else 
        echo "Connection failed" fi; 
done < file
0

CSV is not particularly convenient, but here goes.

while IFS=, read host user pass; do
    if mysql -hu$host" -="$user" -p$"pass" -d"$db" -e exit
    then
        echo "$host: Connection established"
    else
        echo "$host: Connection not established"
    fi
done <file.csv

Notice how if (and generally all the shell's flow control statements) already examines $? behind the scene for you, so you should very rarely need to examine it explicitly in your scripts.

Also, I added the hostname to the output messages, to make them more informative.

If you can have a whitespace-separated input file insted, you can take out the IFS=, and pershaps also simplify some other parts of your processing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.