Monday, January 10, 2011

Checking MySQL connection status

If you are writing a shell script which requires importing / exporting data to / from MySQL database, sometimes, it is important to check whether the username and password are still valid.

To do this, we can check for MySQL exit status. If connection is successful, exit status is 0. If connection failed, exit status is 1.

[root@localhost ~]# mysql --user=root -e exit
[root@localhost ~]# echo $?
0
[root@localhost ~]# mysql --user=root --password=oldpassword -e exit
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
[root@localhost ~]# echo $?
1

The following is an example how we can implement this in our bash script.

#!/bin/bash

  dbuser="root"
  dbpass="oldpassword"

  dbaccess="denied"
  until [[ $dbaccess = "success" ]]; do
    echo "Checking MySQL connection..."
    mysql --user="${dbuser}" --password="${dbpass}" -e exit 2>/dev/null
    dbstatus=`echo $?`
    if [ $dbstatus -ne 0 ]; then
      echo -e "MySQL Username [$dbuser]: \c "
      read dbuser
      # Check if user field is empty
      test "${dbuser}" == "" && dbuser="root";
      echo -e "MySQL Password: \c "
      read -s dbpass
      echo
    else
      dbaccess="success"
      echo "Success!"
    fi
  done

Output:

[root@localhost ~]# ./check_mysql_login.sh
Checking MySQL connection...
MySQL Username [root]:
MySQL Password: (wrong password)
Checking MySQL connection...
MySQL Username [root]: root
MySQL Password: (correct password)
Checking MySQL connection...
Success!
[root@localhost ~]#

Saturday, January 8, 2011

Am I root?

Root privileges is important when doing system wide installation and configuration. How do we determine the script is being run by a root or normal user?

# Check that we are run as root.
# Return 0 if yes, or 1 if not or undeterminable.
function is_root() {
  uid=$(id -u 2> /dev/null)

  if [ -n "$uid" ]; then
    if [ "$uid" != "0" ]; then
      echo "FAILED: You need root privileges to run this script.";
      echo
      return 1
    fi
  else
    echo "Could not detect UID";
    return 1
  fi
}

Wednesday, January 5, 2011

Which distro?

When writing shell script, sometime we need to find out which Linux flavor is running on the machine. I like the following bash script from knowledgetree installer to do the job.

function distro_info() {
  distro=$(lsb_release --short --id)

  case "$distro" in
    "Ubuntu"|"Debian")
      # install deb package using apt-get
      ;;
    "CentOS"|"Fedora"|"RedHatEnterpriseServer")
      # install rpm package using yum
      ;;
    * )
      unsupported_distro
      return 1
      ;;
  esac
}

Related Posts Plugin for WordPress, Blogger...