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.
Asked
Active
Viewed 1.5k times
3 Answers
12
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

quanta
- 51,413
- 19
- 159
- 217
-
2To have your script log in to MySQL without stopping and prompting you for a password, you can create a `.my.cnf` file in your home directory and add a `[client]` block containing `password="my_password"`. Have a look for the section on [user option files](http://dev.mysql.com/doc/refman/5.1/en/option-files.html) in the manual. – Ladadadada Nov 24 '11 at 07:49
4
In MySQL you can use -e from the shell
mysql -e "desc main_db.clients" > /dev/null 2>&1
echo $?

Glen
- 414
- 2
- 8
3
If you want a method that doesn't involve running a mysql client and logging in to the mysql server, you can do this:
if ls -l /var/lib/mysql/database/table.frm 2> /dev/null > /dev/null
then
echo Table exists
else
echo Table does not exist
fi
You will have to replace the path to your data directory, your database name and your table name in the first line.
Caveats:
- This will not work if you are using InnoDB and are not using innodb-file-per-table. i.e. The script can say the table does not exist even though it does.
- It's possible for that file to exist for various reasons including copying tables around using the filesystem or switching from MyISAM to InnoDB. i.e. The script can say that the table does exist even though it doesn't.
It's not as reliable as the other methods presented already because of the reasons above but it avoids the mysql client so it may still be worthwhile.
Note that all methods presented here rely on your getting your own permissions (filesystem or MySQL) correct. If you get them wrong you will most likely get a false negative.

Ladadadada
- 26,337
- 7
- 59
- 90