Linux mount check if mounted

How to check whether a particular directory is mounted? [duplicate]

How to check a particular directory is mounted on the Linux machine. For instance there is a folder named test, I want to check if it is mounted or not.

6 Answers 6

If you want to check it’s the mount point of a file system, that’s what the mountpoint command (on most Linux-based systems) is for:

It does that by checking whether . and .. have the same device number ( st_dev in stat() result). So if you don’t have the mountpoint command, you could do:

Like mountpoint , it will return true for / even if / is not a mount point (like when in a chroot jail), or false for a mount point of a bind mount of the same file system within itself.

Contrary to mountpoint , for symbolic links, it will check whether the target of the symlink is a mountpoint.

As HalosGhost mentions in the comments, directories aren’t necessarily mounted per se. Rather they’re present on a device which has been mounted. To check for this you can use the df command like so:

Here we can see that the directory /boot is part of the filesystem, /dev/hda1 . This is a physical device, on the system, a HDD.

You can also come at this a little bit differently by using the mount command to query the system to see what devices are currently mounted:

Here you can see the type of device and the type of filesystems are currently mounted on your system. The 3rd column shows where they’re mounted on the system within its filesystem.

Источник

Как лучше всего проверить, смонтирован ли том в скрипте Bash?

Как лучше всего проверить, смонтирован ли том в скрипте Bash?

Что мне действительно нравится, так это метод, который я могу использовать так:

Избегайте использования, /etc/mtab потому что это может быть противоречивым.

Избегайте труб, mount потому что это не должно быть так сложно.

(Пробел после /mnt/foo должен избегать совпадения, например /mnt/foo-bar .)

findmnt -rno SOURCE,TARGET «$1» избегает всех проблем в других ответах. Это чисто делает работу с одной командой.

Другие подходы имеют следующие недостатки:

  • grep -q и grep -s являются дополнительным ненужным шагом и не поддерживаются везде.
  • /proc/\* не поддерживается везде
  • mountinfo основан на / proc / ..
  • cut -f3 -d’ ‘ портит пробелы в именах путей
  • Разбирая пробел маунта проблематично. Это страница руководства теперь говорит:

.. Режим листинга поддерживается только для обратной совместимости.

Для более надежного и настраиваемого вывода используйте findmnt (8), особенно в ваших скриптах.

Bash функции:

Примеры использования:

/mnt/dev/sda1 , я мог бы неправильно вещь , которая /dev/sda1 крепится с помощью команды mount | grep ‘/dev/sda1’ . Я не могу получить ложное срабатывание, используя findmnt . Хороший ответ!

Читайте также:  Droidcam linux не работает

Такой сценарий никогда не будет переносимым. Грязный секрет в unix состоит в том, что только ядро ​​знает, где находятся файловые системы, и, за исключением таких вещей, как / proc (не переносимый), он никогда не даст вам прямого ответа.

Обычно я использую df, чтобы узнать, что такое точка монтирования подкаталога и в какой файловой системе он находится.

Например (требуется оболочка posix, например, ash / AT & T ksh / bash / etc)

Кинда рассказывает вам полезную информацию.

Вот что я использую в одном из моих заданий cron резервного копирования rsync. он проверяет, смонтирован ли / backup, и пытается смонтировать его, если это не так (может произойти сбой, потому что диск находится в отсеке горячей замены и может даже не присутствовать в системе)

ПРИМЕЧАНИЕ: следующее работает только на linux, потому что это greps / proc / mounts — более переносимая версия запускает ‘mount | grep / backup ‘, как в ответе Мэтью ..

Так как для монтирования вам в любом случае необходимо иметь каталог, который монтируется, моя стратегия всегда заключалась в том, чтобы создать поддельный файл со странным именем файла, которое никогда не будет использоваться, и просто проверить его существование. Если файл был там, то на этом месте ничего не было смонтировано .

Я не думаю, что это работает для подключения сетевых дисков или подобных вещей. Я использовал его для флешек.

Как насчет сравнения номеров устройств? Я просто пытался придумать самый эзотерический способ ..

В моей логике есть недостаток .

Сообщения об эхо-ошибках, вероятно, являются избыточными, потому что stat также будет отображать ошибку.

Ни один из них не удовлетворяет случаю использования, где данный каталог является подкаталогом в другой точке монтирования. Например, у вас может быть / вещь, которая является монтированием NFS к хосту: / real_thing. Использование grep для этой цели в / proc / mounts / etc / mtab или ‘mount’ не будет работать, потому что вы будете искать точку монтирования, которая не существует. Например, / thing / thingy не является точкой монтирования, но / thing монтируется на хосте: / real_thing. Наилучший ответ, за который проголосовали здесь, на самом деле НЕ «лучший способ определить, смонтирован ли каталог / volumne». Я бы проголосовал за использование «df -P» (режим стандартов -P POSIX) в качестве более чистой стратегии:

Результат выполнения этого будет:

Если вы хотите знать, какова реальная точка монтирования, не проблема:

Результатом этой команды будет:

Все это очень полезно, если вы пытаетесь создать какой-либо chroot, который отражает точки монтирования вне chroot, внутри chroot, через какой-либо произвольный каталог или список файлов.

Источник

Check if directory mounted with bash

I want to check /foo/bar though with a bash script, and see if its been mounted? If not, then call the above mount command, else do something else. How can I do this?

CentOS is the operating system.

8 Answers 8

You didn’t bother to mention an O/S.

Ubuntu Linux 11.10 (and probably most up-to-date flavors of Linux) have the mountpoint command.

Here’s an example on one of my servers:

Actually, in your case, you should be able to use the -q option, like this:

Hope that helps.

Running the mount command without arguments will tell you the current mounts. From a shell script, you can check for the mount point with grep and an if-statement:

Читайте также:  Xcode для windows есть

In my example, the if-statement is checking the exit code of grep , which indicates if there was a match. Since I don’t want the output to be displayed when there is a match, I’m redirecting it to /dev/null .

The manual of mountpoint says that it:

checks whether the given directory or file is mentioned in the /proc/self/mountinfo file.

The manual of mount says that:

The listing mode is maintained for backward compatibility only. For more robust and customizable output use findmnt(8), especially in your scripts.

So the correct command to use is findmnt , which is itself part of the util-linux package and, according to the manual:

is able to search in /etc/fstab, /etc/mtab or /proc/self/mountinfo

So it actually searches more things than mountpoint . It also provides the convenient option:

Explicitly define the mountpoint file or directory. See also —target.

In summary, to check whether a directory is mounted with bash, you can use:

Источник

How to Check if a Filesystem is Mounted in Linux?

To start working, you must have any Linux distribution installed on your system. Login from your Linux system and open the command terminal. Make sure you have the “util-linux” package installed on your system to start checking the mounted filesystem. For this purpose, try the below “apt” command followed by the keyword “install” in a shell. Instantly, the installation will be completed, and you can now check the mounted filesystem.

There are many methods available to check the file system on your system. We will illustrate each one of them one by one.

Method 01: Using Findmnt Command

Our first and most used way in the Linux system to know the filesystem type is the “findmnt” command. The “findmnt” command helps us find all the mounted filesystems. Let’s start working on it. To see the list of mounted filesystems, type the simple “findmnt” command in the shell as below, which will list all the filesystems in a tree-type format. This snapshot contains all the necessary details about the filesystem; its type, source, and many more. It is clear from the image that our main filesystem is “ext4”.

Let us display the filesystems in a simple format using the below “findmnt” command with a “-l” flag.

We can list the type of our mounted filesystem using the findmnt command along with the “-t” flag followed by the name of the filesystem, e.g., “ext4”. So, execute the below-stated command in the shell. The output shows the information regarding the “ext4” filesystem.

To see the “df” style list of output about the filesystem, you have to use the below command. You can see that it will show extra information regarding the filesystems and their sources.

You can use the modified form of this command as follows:

If you want to search for the configured filesystem in a particular device, you can do so using the below command. You can see that the output shows the “vfat” type filesystem for the specific device.

Читайте также:  Samsung rv520 не устанавливается windows 10

If you want to see the mount point of a filesystem, try using the below “findmnt” command followed by the backslash “/” sign.

If you want to know more details about the filesystem, use the man command as follows:

The output is shown below.

Method 02: Using Blkid Command

In most cases, the “findmnt” command will be enough in knowing the filesystem’s type, but there are some alternative commands for this purpose. One of them is the “blkid” command which we don’t need to mount. After the execution of the “blkid” command below, along with the “sudo” keyword, we will be able to display all the block devices along with the filesystem type.

We can use the “blkid” command to know the filesystem for the particular device.

To see extra details about the filesystem, try the below command:

For further details try the man command below:

The output is given below.

Method 03: Using DF Command

The DF command is cast-off to know the disk space usage of the filesystem. Use it with the “-T” flag to know all the filesystem’s types.

Go through the man page to know more.

The detail is given in the snapshot.

Method 04: Using File Command

Another method to check the mounted file system is using the “file” command in the shell. You can use it for files having no extension. Hence, execute the below command to know the filesystem for a partition. It may require your password to function.

To have extra information, try the below man command in the shell.

You can see the details on the main page as shown in the appended image.

Method 05: Usinf Fsck Command

The “fsck” command may be used to verify or restore the reliability of a filesystem by providing the partition as an argument. You will decide what sort of filesystem it is.

For further details, have a look at the main page.

And you can see the details shown below.

Method 06: Using Fstab Command

Another new way to view the filesystem is using the “fstab” in the cat command. Therefore, try executing the below cat command in the shell.

For extra details, try the same man command along with the keyword “fstab”.

Now you will be having details about the filesystem, as shown in the image attached.

Method 07: Using Lsblk Command

The “lsbkl” command will show the filesystem types and the devices.

Run the below man command to see the details.

And the extra information regarding the filesystem is displayed below.

Method 08: Using grep Command

Last but not least, the “grep” command is used to check the filesystem.

Conclusion:

We have done all the commands to check the mounted filesystem. I hope you can easily check the mounted filesystem in your Linux distribution.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.

Источник

Оцените статью