How to run a command only if a certain drive is mounted?

So I want to make a script that runs a command if a drive is mounted, if not it should run a different command. I found this:

#!/bin/sh

mounted=`df | grep "/mountpoint"`

if [[ mounted != "" ]] ; then
	command_1
else
	command_2
   
fi

But it only runs the first command if that drive is mounted, if it isn’t then it complains that the file or drive does not exist. It doesn’t try to run the second command.

Any help is appreciated.

Using df and grep like that is terrible. Too many ways for that to fail.

Although the real problem is that you didn’t properly reference the variable. It should be "$mounted" in the if

Either way, try this:

if [[ -n $(findmnt /mountpoint) ]] ; then
	command_1
else
	command_2
fi
2 Likes

:partying_face: Thank you!

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.