简体   繁体   中英

Bash: Close MySQL connection when server fails

I have a simple script to connect to a extern MySQL server.

#!/bin/bash
server=1.2.3.1
port=3306
user=root
pass=root
db=radius

output=$(mysql -N -h $server -u $user -p$pass $db -e  "select * from table)
echo "$output"

The problem is when the mysql service fails on server 1.2.3.1, because the script gets stucked waiting for answer a long time!

How can I wait only for 1 second and if server doesn't respond, the script kills the process? Or how can I check if the service is up on the remote server before?

Regards.

I didn't test this out but I suppose you could set a timer and then test whether your result has a value.

#!/bin/bash
server=1.2.3.1
port=3306
user=root
pass=root
db=radius

output=$(mysql -N -h $server -u $user -p$pass $db -e  "select * from table)
sleep 1
if ! [[ $output ]]
   mysql exit
fi
echo "$output"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM