How can I check if mysql is installed using a bash script?
14,680
Solution 1
type mysql >/dev/null 2>&1 && echo "MySQL present." || echo "MySQL not present."
Solution 2
If you exclusively use your Ubuntu package manager for MySQL installation, then you can just use the dpkg front-end to dpkg-query to find out whether the package is installed.
# Look up package with dpkg-query.
if dpkg --list mysql-client | egrep -q ^ii; then
:
fi
This is fast and reliable, but obviously only works when you use your Ubuntu system packages.
Related videos on Youtube
Author by
Kit Sunde
CTO at Media Pop, hire us for DevOps and product development
Updated on September 18, 2022Comments
-
Kit Sunde over 1 year
I need to check if mysql is installed from within a bash script. What would be an efficient way of doing that? I thought I could do this:
if [ ! -f `which mysql` ] ; then echo "foo" fi
But I think I might be confused about something. What would be a better solution? It should be portable and work on both
Ubuntu
andOSX
.-
Admin almost 12 yearsWhat exactly confuses you about the code you posted? What did you expect it to do, and what does it do instead?
-
Admin almost 12 years
which
only returns regular files anyway. This test will always be false. -
Admin almost 12 years@kopischke I expected
which mysql
to give back the path to mysql that then is checked if it's a file or not. But it seems to just not work. -
Admin almost 12 yearsThis will also potentially break in any shell where
[
is an external command, as ifwhich
does not return anything,-f
will be missing an argument. -
Admin almost 12 yearsAlso, using which will fail if mysql is an alias.
-
-
Bram almost 12 yearsWhat is the problem with searching only in
$PATH
? If it is installed in a non-standard location you need to know that location to run it anyway. And if you know the non-standard location it probably doesn't make much sense to run a script that checks if it is installed or not. -
George M almost 12 years@Bram Being installed does not implicitly mean it's going to be in a standard location. What if, as root, I want to know how many mysqld binaries users have compiled and installed on the system? It could be in /opt (not usually considered standard), could be under some user /home directory, could be in a subdirectory under /usr/local. There could also be multiple versions of mysqld installed. Assuming the binary is going to be in $PATH or it's irrelevant is not, in my opinion, a good view to have.
-
clerksx almost 12 years@Bram - I have absolutely no idea. I'm just providing an alternative for uther's answer.
-
Gilles 'SO- stop being evil' almost 12 yearsI do not recommend running
find
over the entire filesystem. It's rude. You may be traversing external drives, network mounts, … Ifmysql
isn't in the path, it might as well not be installed. There might be a non-working installation of mysql that's not in the path on purpose.