Mysql – From a shell script, how can I check whether a table in MySQL database exists or not

MySQLshellshell-scripting

I am trying to write a script which allows a user to select the what manipulation he needs to do on a table. I want to check if the table exists or not. If it exists I will continue the other things or else I exit saying table doesn't exist. How might I achieve this.

Best Answer

if [ $(mysql -N -s -u root -p -e \
    "select count(*) from information_schema.tables where \
        table_schema='db_name' and table_name='table_name';") -eq 1 ]; then
    do something
else
    echo "table <table_name> does not exist"
    exit 1
fi
  • -N to skip column names
  • -s for nontabular output