开发者

Shell script to know whether a filesystem is already mounted

I have a tmpfs file sys开发者_运维问答tem mounted on a particular directory. I want to write a shell script to check whether the tmpfs filesystem is already mounted on the directory.


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.


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


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

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

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


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...


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.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜