samedi 7 octobre 2017

bash script - multiple complex conditionals

I have the following in a bash script, which checks if args have been supplied and then tests a mysql connection from passed variables (yes i know i should use ssh, but it's not an option).

if [ $# = 6 ];
then
    if mysql -u "${REMOTE_DB_USER}" -p"${REMOTE_DB_PASS}" -h "${REMOTE_DB_URL}" "${REMOTE_DB_NAME}" -e ";" ;
    then
        echo "6 args found & mysql connect worked"
        # Do stuff...
    fi
fi

Though my script works fine I'm wondering if there's a more elegant way to write this as a single if statement. I've tried wrapping the conditionals in square brackets, moving quotes and using command (seems wrong) but I just can't seem to get it right.

For example, the following gives me an error: too many arguments

if [ $# = 6 ] && [ mysql -u "${REMOTE_DB_USER}" -p"${REMOTE_DB_PASS}" -h "${REMOTE_DB_URL}" "${REMOTE_DB_NAME}" -e ";" ] ;
then
    # do stuff...
fi

Now I'm thinking maybe I should put the mysql check in a function? I wanted to check with the community for some direction on the right way to go about wrapping and testing for multiple conditionals so that I don't start building bad habits right away.

Apologies if this is a duplicate, but I've been searching for a bit to no avail.

Aucun commentaire:

Enregistrer un commentaire