Shell script to know whether a filesystem is already mounted

本小妞迷上赌 提交于 2019-12-18 18:51:33

问题


I have a tmpfs file system mounted on a particular directory. I want to write a shell script to check whether the tmpfs filesystem is already mounted on the directory.


回答1:


You can check the type of the filesystem.

$ stat -f -c '%T' /
xfs
$ stat -f -c '%T' /dev/shm
tmpfs

You could also check whether a directory is a mountpoint by comparing its device with its parent's.

$ stat -c '%D' /
901
$ stat -c '%D' /home
fe01
$ stat -c '%D' /home/$USER
fe01



回答2:


There's a tool specifically for this: mountpoint(1)

if mountpoint -q "$directory" ; then
    echo it is a mounted mountpoint
else
    echo it is not a mounted mountpoint
fi

And you don't even have to scrape strings to do it!

Note that I find this tool in Debian's initscripts package. How available it is elsewhere is not something I can comment on.




回答3:


Something like this, while hackish, should do the trick:

FS_TO_CHECK="/dev" # For example... change this to suit your needs.

if cat /proc/mounts | grep -F " $FS_TO_CHECK " > /dev/null; then
    # Filesystem is mounted
else
    # Filesystem is not mounted
fi



回答4:


I know this thread is old, but why not just use df and grep for the required path to the mountpoint? i.e. like this:

df /full/path | grep -q /full/path

grep returns true if mounted, false if not. So we just need to test it like this:

df /mnt/myUSBdisk | grep -q /mnt/myUSBdisk && echo "Mounted" || echo "Not mounted"

Easy peasy...




回答5:


You could use df, try man df.

df 'directory' | awk '{print $1, $6}'

will give you sth like:

Filesystem Mounted
/dev/sda5  'some_dir'

you can then add a check if the directory 'some_dir' is same as 'your_dir', and filesystem is same as yours.




回答6:


Check /proc/mounts. If you grep on the filesystem name and the path you want it mounted (maybe even a specific line with all options included) you can tell if the filesystem is mounted.

if [ "`grep "tmpfs /lib/init/rw tmpfs rw,nosuid,mode=755 0 0" /proc/mounts`" != "" ]
then
  echo Mounted.
else
  echo Not mounted.
fi



回答7:


if mount -l -t tmpfs | grep "on $directory "
then
    echo "it's mounted"
fi



回答8:


mountpoint is much more elegant and is in sysvinit-tools CentOS 6+++



来源:https://stackoverflow.com/questions/4212522/shell-script-to-know-whether-a-filesystem-is-already-mounted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!