Linux check mount point

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

How to check whether or not a particular directory is a mount point? For instance there is a folder named /test that exists, and I want to check if it is a mount point or not.

You don’t mount directories on Linux. You mount devices to particular directories. Checking to see if something is mounted is as simple as looking at the output of the mount command.

The answers below will show you how to examine the mount table, but a simpler solution is to create a file in the mount point directory before anything is mounted on it. Call it anything you like, but one example is NOTMOUNTED . When you can see the file, the directory is not a mount point, and when you don’t, it is.

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:

if mountpoint -q -- "$dir"; then printf '%s\n' "$dir is a mount point" fi 

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:

perl -le '$dir = shift; exit(1) unless (@a = stat "$dir/." and @b = stat "$dir/.." and ($a[0] != $b[0] || $a[1] == $b[1]))' "$dir" 

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.

At least on Ubuntu, the output of mountpoint already says «$dir is a mountpoint» ,so you don’t need the if part around it.

@SergiyKolodyazhnyy the -q means quiet output, so in this case, the output is being suppressed and then replaced by custom output. Unnecessary, but yeah.

@Wyrmwood I know what the options are. What I’m saying is that mountpoint «$dir» already does exactly the same as the 3-line if statement does here. Functionally they’re the same. Such use of mountpoint -q in if statement can be used when you want to perform some action based on the exit status, but for printing the message to user its unnecessary — it’s already the default behavior of the program.

Читайте также:  Сохранения данных kali linux

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:

$ df -h /boot/ Filesystem Size Used Avail Use% Mounted on /dev/hda1 99M 55M 40M 59% /boot 

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:

$ mount | column -t /dev/mapper/VolGroup00-LogVol00 on / type ext3 (rw) proc on /proc type proc (rw) sysfs on /sys type sysfs (rw) devpts on /dev/pts type devpts (rw,gid=5,mode=620) /dev/hda1 on /boot type ext3 (rw) tmpfs on /dev/shm type tmpfs (rw) /dev/mapper/lvm--raid-lvm0 on /export/raid1 type ext3 (rw) none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw) sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw) nfsd on /proc/fs/nfsd type nfsd (rw) 

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.

Источник

How do I check where devices are mounted?

What is the command that lets me see what and where devices are mounted? I’m having trouble changing songs on my old iPod, and I have a feeling it’s because of the mount point.

3 Answers 3

There are at least three programs I know of that list device mount points:

    mount — mount a filesystem (used for general mount info too):

$ mount /dev/sda3 on / type ext4 (rw,errors=remount-ro) proc on /proc type proc (rw,noexec,nosuid,nodev) sysfs on /sys type sysfs (rw,noexec,nosuid,nodev) . /dev/mapper/lvmg-homelvm on /home type btrfs (rw,relatime,compress=lzo,space_cache) /dev/sda5 on /home/muru/arch type btrfs (rw,relatime,compress=lzo,space_cache) binfmt_misc on /proc/sys/fs/binfmt_misc type binfmt_misc (rw,noexec,nosuid,nodev) systemd on /sys/fs/cgroup/systemd type cgroup (rw,noexec,nosuid,nodev,none,name=systemd) 
$ df Filesystem 1K-blocks Used Available Use% Mounted on /dev/sda3 30832636 11993480 17249912 42% / none 4 0 4 0% /sys/fs/cgroup . /dev/sda5 31457280 3948600 25396496 14% /home/bro3886/arch 
$ lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sda 8:0 0 465.8G 0 disk ├─sda1 8:1 0 100M 0 part ├─sda2 8:2 0 58.5G 0 part ├─sda3 8:3 0 30G 0 part / ├─sda4 8:4 0 1K 0 part ├─sda5 8:5 0 30G 0 part ├─sda6 8:6 0 339.2G 0 part │ └─lvmg-homelvm (dm-0) 252:0 0 1.2T 0 lvm └─sda7 8:7 0 8G 0 part [SWAP] sdb 8:16 0 931.5G 0 disk └─sdb1 8:17 0 931.5G 0 part └─lvmg-homelvm (dm-0) 252:0 0 1.2T 0 lvm 

Of these three, mount lists all the mountpoints, AFAICT. The others have their weaknesses.

    findmnt suggested by @webwurst is now my favourite tool for the job. It’s a Swiss Army knife when it comes to output control (newer versions can output in JSON too):

$ findmnt / TARGET SOURCE FSTYPE OPTIONS / /dev/sda1 ext4 rw,relatime,errors=remount-ro,data=ordered $ findmnt / -no source /dev/sda1 $ findmnt / --json < "filesystems": [ ] > $ findmnt / --df SOURCE FSTYPE SIZE USED AVAIL USE% TARGET /dev/sda1 ext4 40.2G 25.8G 12.5G 64% / 

Источник

Читайте также:  Hikvision storage server linux

Check logical volume mount point (command line)

With GNOME Disks utility, I can check whether a logical volume is mounted: enter image description here And where is it mounted: enter image description here How can I get this information from the command line? Having, for example, the logical volume UUID, I would like to know if it is mounted and where.

5 Answers 5

Just use lsblk . It prints all disks and their corresponding mount points. Including LVM, MD RAID, etc.

I would mention the -o MOUNTPOINT option if you are only interested in getting the mount point (that was the question). And the -n option to avoid printing the column names.

To find all mount points or pipe it through grep , if you know device name, e.g.:

To find a specific UUID, just use:

findmnt -rn -S UUID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -o TARGET 

To use this simple method, one needs to know the UUID of the partition.

Therefore the step by step guide would be:

Then looking up its partition UUID with:

And finally just look up the mount point:

findmnt -rn -S UUID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -o TARGET 
total 0 crw------- 1 root root 10, 236 Nov 13 05:15 control lrwxrwxrwx 1 root root 7 Nov 13 05:18 mint--vg-root -> ../dm-0 lrwxrwxrwx 1 root root 7 Nov 13 05:18 mint--vg-swap_1 -> ../dm-1 
/dev/dm-0: UUID="32ee47f8-02df-481d-b731-6e67734999ca" TYPE="ext4" 
findmnt -rn -S UUID=32ee47f8-02df-481d-b731-6e67734999ca -o TARGET 

Which is the actual mount point in this VM.

Now I get it. What you propose is using the partition UUID. I was asking for the logical volume UUID in my question (the one you see with lvdisplay ). I guess your solution is valid as well.

Having the UUID of a logical volume, find out whether it’s mounted and where.

sudo lvs -o vg_name,name,uuid

This will list all known logical volumes, with their UUIDs, names and the names of the volume group containing them. Remember the ‹vgname› and ‹lvname› corresponding to the given UUID.

UUID='B3629a-B11c-4aec-bE1f-rUdk-a6d2-dd0a6bc' LVName="$( sudo lvs -o vg_name,name,uuid | grep "$UUID" | sed -e 's/^\s*\(\S\+\)\s\+\(\S\+\).*/\1-\2/' )" if [ -z "$LVName" ] ; then echo "Cannot find logical volume with UUID=$UUID" else MountPoint="$( findmnt -l | grep " /dev/mapper/$LVName" | awk '< print $1 >' )" if [ -z "$MountPoint" ] ; then echo "Logical volume /dev/mapper/$LVName with UUID $UUID is not mounted" else echo "Logical volume /dev/mapper/$LVName with UUID $UUID is mounted on $MountPoint" fi fi 

Источник

Как посмотреть точки монтирования Linux

Одно из самых заметных отличий Linux от Windows, это то, что операционная система позволяет пользователям прозрачно управлять монтированием разделов диска. Это позволяет гибким образом настроить структуру каталогов, использовать несколько файловых систем, где каждая будет выполнять свое предназначение.

Читайте также:  Linux монтирование флешки ntfs

Благодаря такой возможности, вы можете переустановить операционную систему и не потерять пользовательские файлы, обращаться к параметрам ядра с помощью каталогов /proc и /sys, а к блочным устройствам с помощью каталога /dev. В этой статье мы разберемся что такое точки монтирования, а также как посмотреть точки монтирования в Linux.

Что такое точки монтирования в Linux?

Чтобы понять как тут всё происходит, давайте проведём аналогию. Допустим, у вас есть большое поле и вы на нём хотите посадить картошку. Но выращивать вы хотите несколько сортов. Поэтому вы делите поле на несколько участков и на каждом из них садите нужный сорт. Когда приходит время собирать урожай, независимо от сорта картошку надо выкопать и вывезти, а к полю идёт только одна дорога и вся полученная картошка будет вывезена именно по ней не зависимо от того, с какого участка она была собрана.

Допустим, у вас есть один большой жесткий диск, на который надо записать данные. Это наше поле. Но вам надо файловая система без журналирования для каталога /boot, отдельная файловая система для корня и для /home. Поэтому жесткий диск разбивается на разделы. Дальше эти разделы надо отформатировать в нужную файловую систему. Это аналогия сорта картошки. А монтирование — это аналогия дороги, по которой картошку вывозят с поля. На каком бы разделе диска или части оперативной памяти не располагались данные, получить к ним доступ вы сможете только с помощью корневого каталога /. Все разделы монтируются сюда, если не к самому корню, то в одну из папок. Такая папка и называется точкой монтирования и её содержимое во время монтирования заменяется на содержимое раздела.

Как посмотреть точки монтирования?

Для просмотра точек монтирования можно использовать команду mount. Её надо запустить без параметров:

С появлением технологии snap и flatpack, точки монтирования Linux слегка засорены монтированием различных snap пакетов и их содержимого к файловой системе, но всё же здесь можно разобрать и смонтированные жесткие диски. Чтобы отфильтровать только жесткие диски используйте утилиту grep:

Не только посмотреть, но и настроить точки монтирования можно с помощью файла /etc/fstab. Здесь перечислены все разделы диска, которые монтируются к системе.

Более подробно о его настройке я писал в этой статье.

Выводы

Из этой статьи вы узнали что такое точки монтирования Linux, а также как их посмотреть и настроить. А что вы думаете по поводу них? Удобнее ли это чем в Windows? Напишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

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