bash: test if device is mounted
in a bash script, is there a way to test if a device is mounted using primaries (ie. [ -f /foobar/foo.bar ] etc...) or "test"
basically want to do an if, then, else that varies on whether or not a specific device is mounted. the dev always mounts to the same location set through fstab, so using the mounted location is a possibility too. i just can't seem to find any specifics that differ when mounted or not. if worse comes to worse, i can just put a file on that device & use Code:
if [ -f /foo/bar/.randomfile ]; then thanks in advance. |
grep the output from df.
|
If you know it is always going to be mounted at the same place then you can do something simple like this
Code:
if [ $(mount | grep -c /mnt/MOUNTEDDIR) != 1 ] |
Same thing as syg00 and shadowsnipes but, FWIW, I'd write it
Code:
if mount | grep -q /mnt/MOUNTEDDIR; then... |
great.
thanks for the quick replies. i totally spaced out that mount & df give a list of what's mounted. oops. :( |
Many Linux distros have the mountpoint(1) command which can explicitly be used to test if a directory is a mountpoint.
Code:
#!/bin/bash There is no equivalent in BSD as far as I can tell. Note that if using the mount + grep -c method, you may need to use a regular expression to test the mountpoint. I have a an old drive whose mountpoints that were previously mounted at the root level are now mounted one level down i.e. the old disk has mount points like /olddisk/usr, /olddisk/home etc. The current /usr partition is also a mountpoint. A simple grep -c on /usr will therefore return 2. |
Good note. <pedantic>Though, I'd still write it as
Code:
#!/bin/bash Also, technically, when using the old style test, it should be a single '=' (for string comparison) or '-eq' for integer comparison rather than the double '==' (ash, for instance, will throw an 'unexpected operator' error). And, if using bash as our shebang declares, it should use the new style test, anyway. Just making the command's exit status the conditional avoids the historical baggage of the tests.</pedantic> Still, the essence of it is that mountpoint, if available, would definitely have been the command to use. |
try the proc file system
I know that this thread is not current, but I had the same query as to how to do this from a program. What I found is that /proc/self/mounts has the same info as what mount gives and it also has info on mounts that have not been made through the mount program - ie. mounts that have been made through the mount system call.
Explicitly, what you would do is the following command (or equivalent): grep mountpoint /proc/self/mounts |
All times are GMT -5. The time now is 05:40 AM. |