How to unmount disk linux
How to unmount disk linux
Как размонтировать диск в Linux
При прекращении работы с диском в Linux, чтобы полностью закрыть к нему доступ и избежать повреждения данных при выключении, следует его размонтировать. Для этих целей существует утилита umount, которая запускается через терминал.
В данной статье мы разберемся с ее синтаксисом и опциями. А заодно рассмотрим, как размонтировать диск в Linux. Для удобства все будет описано на конкретных примерах.
Синтаксис и опции umount
В отличие от mount, команда umount Linux размонтирует указанный диск. В результате он становится недоступным. Это относится и к любым подключенным устройствам. У команды достаточно понятный синтаксис:
$ umount опции /путь/к/точке/монтирования
$ umount опции название_устройства
Перейдем к списку доступных опций:
Это были основные опции, которые могут пригодиться при выполнении команды umount. А теперь перейдем к практическим примерам ее использования.
Как размонтировать диск в Linux
Для удобства мы разберем четыре популярных сценария, с которыми может столкнуться каждый: размонтировать диск, все подключенные устройства и разделы, конкретный путь и рекурсивное размонтирование.
1. Размонтировать диск
В качестве примера возьмем USB-диск, на который были загружены бэкапы данных. Перед отключением от компьютера его следует размонтировать. Сначала посмотрим полный список доступных дисков:
USB-диск объемом 500 ГБ маркирован как sdb1. Для его размонтирования следует выполнить команду:
sudo umount /dev/sdb1
В результате диск размонтируется. Вы можете посмотреть, что он пропал из списка доступных устройств в файловом менеджере Linux.
Если диск в настоящий момент занят, то возникнет ошибка. С помощью опции -l его получится размонтировать, когда он освободится:
Ну а опция -f нужна для принудительного размонтирования. В таком случае все выполняемые операции незамедлительно прервутся, и ждать ничего не придется:
Если при размонтировании у вас возникает ошибка Device or resource busy, посмотрите в этой статье как её решить.
2. Размонтировать все устройства
Опция -a, которая упоминалась в самом начале списка, отвечает за размонтирование всех смонтированных файловых систем. Но есть несколько разделов с исключениями: roc, devfs, devpts, sysfs, rpc_pipefs и nfsd. Запускать ее нужно с осторожностью, ведь будут размонтированы важные разделы.
Перед выполнением основной команды вы можете посмотреть то, какие устройства будут затронуты. Для этого пригодятся опции —fake (fake-команда) и -v для вывода подробной информации:
В результате отобразится полный список путей и устройств, которые будут размонтированы. Для полноценного запуска процедуры выполните команду без опций —fake и -v:
А если нужно размонтировать все устройства принудительно, то дополнительно понадобится опция -f:
3. Размонтировать путь
Если вы хотите отключить конкретный путь от корневой файловой системы Linux, то подход будет несколько иной. В качестве примера возьмем каталог, расположенный по пути /run/lock/tmpfs. Команда для размонтирования будет выглядеть следующим образом:
sudo umount /run/lock/tmpfs
Если конкретно сейчас путь занят, то в терминале появится ошибка busy. В таком случае действие можно выполнить принудительно с помощью опции -f. Или дождаться, когда путь освободится с опцией -l.
4. Рекурсивное размонтирование
Для рекурсивного размонтирования определенной директории, например, каталога, к описанной выше команде следует добавить опцию -R или —recursive:
Но при запуске рекурсивного размонтирования в утилите umount стоит помнить важный нюанс. Выполнение команды будет прервано при возникновении любой ошибки. А отношение между точками монтирования регулируются правилами в документе /proc/self/mountinfo. Если же вы хотите получить дополнительную информацию при рекурсивном размонтировании, то воспользуйтесь опцией -v (Verbose mode):
Выводы
В начале данной статьи мы описали утилиту umount Linux, особенности ее синтаксиса и доступные опции. А затем перешли к конкретным примерам использования, с которыми может столкнуться каждый. По описанным принципам можно понять, как размонтировать диск linux, а также любой раздел или директорию.
How To Unmount Disk in Linux, Ubuntu, CentOS with umount Command
Linux distributions like Ubuntu, Debian, CentOS, RHEL, and others use disks by mounting them to the file system. We have already examined mount command in the following tutorial. In this tutorial we will learn how to umount the disk in a Linux system.
Before Unmount
Before unmount we should be sure that all changes are written to the file system and disk. So we need to close open files that reside in the file system we want to unmount.
List Mounted File Systems
Before unmounting filesystems and partitions we may need to list currently mounted filesystems and partitions.We can use the command mount in order to list currently mounted file systems and partitions with some information.
Alternatively lsblk command can be used already mounted file systems which provides more hierarchical list and eliminate unnecassary information.
Umount Specified Partition
When the unmount is completed succesfully there will be no message about the process which simply sign the succesfull unmount. If there are some messages which are generally related with the error this means some error which prevents the unmount operation.
Unmount All Partitions
Force To Unmount
Alternatively we can list already opened file descriptor with the lsof command like below. We will just provide the mount path where the opened files will be list.
Verbose
How to Mount and Unmount Filesystem / Partition in Linux (Mount/Umount Command Examples)
Once you insert new hard disks into your system, you’ll typically use utilities like fdisk or parted to create partitions. Once you create a partition, you’ll use mkfs command to create ext2, ext3, or ext4 partition.
Once you create a partition, you should use mount command to mount the partition into a mount point (a directory), to start using the filesystem.
This tutorial explains everything you need to know about both mount and umount command with 15 practical examples.
The general mount command syntax to mount a device:
1. Mount a CD-ROM
The device file for CD would exist under /dev directory. For example, a CD-ROM device will be mounted as shown below.
In the above example, the option “-o ro” indicates that the cdrom should be mounted with read-only access. Also, make sure that the destination directory (in the above example, /mnt) exist before you execute the mount command.
2. View All Mounts
After you execute mount a partition or filesystem, execute the mount command without any arguments to view all the mounts.
In the example below, after mounting the USB drive on a system, the output of mount looks like the below. As seen below, the USB device (i.e:/dev/sdb) is mounted on /media/myusb, which is displayed as the last line in the mount command.
You can also use df command to view all the mount points.
3. Mount all the filesystem mentioned in /etc/fstab
Example /etc/fstab file entries:
Some filesystem are not unmounted as its busy or currently in use. Note that the files /etc/mtab and /proc/mounts contents would be similar.
4. Mount only a specific filesystem from /etc/fstab
When you pass only the directory name to mount, it looks for mount point entries, if not found, then search continuous for a device in /etc/fstab and gets mounted.
As seen above, /mydata directory is not a mountpoint, but it is present in /etc/fstab.
If you execute the same again, you would get the error message as follows:
Here you may also pass the device name instead of directory name (to be picked up from /etc/fstab file).
Note that the files /etc/mtab and /proc/mounts contents would be similar.
5. View all mounted partitions of specific type
As seen above, /dev/sda6 is the only ext2 partition and /dev/sda5 is the only ext4 partition accordingly.
6. Mount a Floppy Disk
The device file for floppy disk would exist under /dev directory. For example, a floppy disk will be mounted as shown below.
After the successful mount, you would be able to access the contents of the floppy disk. Once you are done with it, use umount before you physically remove the floppy disk from the system.
7. Bind mount points to a new directory
The mountpoint can be binded to a new directory. So that you would be able to access the contents of a filesystem via more than one mountpoints at the same time.
Now the bind is done and you might verify it as follows,
As seen above the bind is done properly. So when you do modification in filesystem in one place, you can see those reflection of it in other mount point as shown below:
8. Access contents from new mount point
Mount allows you to access the contents of a mount point from a new mount point. Its nothing but move a mounted tree to another place.
Once its done, you cant use the old mount point as its moved to a new mount point and this can be verified as shown below:
9. Mount without writing entry into /etc/mtab
You cannot see any entry for this /mydata in mount command output and as well from /etc/mtab file as follows:
Access the contents of a mounted directory /mydata:
10. Mount filesystem with read or read/write access
ext3 and ext4 filesystem would still allow you to do write operation when the filesystem is dirty. So, you may have to use “ro,noload” to prevent these kind of write operation.
11. Remount the mounted filesystem
In order to mount the already mounted filesystem, use remount option and its normally used to remount the filesystem with read/write access when its previously mounted with read access.
The /mydata mount point is going to be remounted with read/write access from read access as shown below:
12. Mount an iso image into a directory
The iso image can be mounted as shown below:
13. Unmount more than one mount points
Umount allows you to unmount more than mount point in a single execution of umount of command as follows:
14. Lazy unmount of a filesystem
15. Forcefully unmount a filesystem
If this doesn’t work for you, then you can go for lazy unmount.
Meanwhile, you can also have a look at ps command output that which process is presently using the mountpoint as shown below:
You can also execute fuser command to find out which process is holding the directory for operations.
It gives you the process id with username (nothing but the owner of the process). If you know what that process is, you may want to stop that process and then try the umount again.
If you enjoyed this article, you might also like..
Comments on this entry are closed.
Thank you for this stuff….. But i have an another doubt is it possible to mount the NTFS filesystem in the system……………….?
Quote”after mounting the USB drive on a system”…….
Maybe you should tell us about HOW to mount an USB 🙂
At one time, the way I did it involved figuring-out which device in the hub it was attached to. I would plug the device in, wait 5 seconds then issue a dmsg command and filter it on SCSI devices (#dmsg | grep sd). Now, it is automatically mounted under /media/usb.
Thanks, very useful article
Usage: ntfs-3g [-o option[,…]]
Options: ro (read-only mount), remove_hiberfile, uid=, gid=,
umask=, fmask=, dmask=, streams_interface=, syncio.
Please see the details in the manual (type: man ntfs-3g).
Example: ntfs-3g /dev/sda1 /mnt/windows
Further Info: Ntfs-3g news, support and information: http://ntfs-3g.org
helpfull suggestion!
much thanks.
Hi, It was very good. Thanks a lot.
I am adding one thing which is missing is SAN share nfs & cifs volumes mounting.
# mount IPAddress:/vol/vol_nfs_01_10/qtree_01 /opt/myshare
SAN volume share given by SAN Team.
Install ntfs-3g pkg to mount NTFS FS.
Hope this thread is still active! I’ve setup Cygwin on a windows box for a subversion solution and trying to map SVN repository which is on a network share. I am able to do it by net use command but I need a permanent mount which works regardless of whether the server is being RDPed or otherwise.
I’ve update FSTAB with the following:
//NTSHARE/SVNREP /home/mnt user,rw,auto,errors=remount-ro 0 0
But it doesn’t seem to mount the share as I’d hoped. What am I missing? Any help on this would be greatly appreciated. Thanks.
Very useful..
Thanks.
Keep This Good Work On…
Hello, I have a question. What command I need to mount the “var” folder on a magento install. Server is running on centOS.
I have a simple question that I am just missing. How can I tell what type a drive is to mount it. You use several examples above but there is not an explanation to fine the type. Any help would be greatly appreciated.
Thanks your article!
Your example is very useful to me!
Write the useful article like this for linux beginner!
Wish your help!
In Cent Os7, on booting, which script file is the first executed?
I want install C++ software in ubuntu 14.04, so can anyone help me?
Should this be an issue. Linux is still work in progress. I just need to access my drives and that’s all. why the hell should i go through all these troubles just to access my files on another drive?
I am running Trisquel GNU/Linux 7.0 Mini, booting from a USB flash drive. The files I want to access are on the hard drive of the laptop.
I think I am clear on this… I need to know the name of the file system on the hard drive and the type of extension in order to mount it and get at my files? I think this is right. It has to be, because Trisquel does not mount the file systems on the hard drive at bootup. It simply shows they exist by labeling them, “500 GB Volume”, and so on down the line. And when I try to mount them by clicking on them, Trisquel tells me that I do not have permission to mount these file systems, nor does it tell me the names or type of the file systems. I am sure I need to know what they are already. I do know what they are, but I do not want to try these mounting commands until I am clear on what I am doing. I don’t want to screw up any of my drives or files, don’t want to rename them, etc. I only want to leave them as they are, access them from Trisquel, and get to work on them.
How to unmount disk linux
A filesystem in this context is a hierarchy of directories that is located on a single partition (logically independent section of a hard disk drive) or other device, such as a CDROM, DVD, floppy disk or USB key drive, and has a single filesystem type (i.e., method for organizing data).
Mounting refers to logically attaching a filesystem to a specified location on the currently accessible (and thus already mounted) filesystem(s) on a computer system so that its contents can be accessed by users. Unmounting refers to logically detaching a filesystem from the currently accessible filesystem(s).
All mounted filesystems are unmounted automatically when a computer is shut down in an orderly manner. However, there are times when it is necessary to unmount an individual filesystem while a computer is still running. A common example is when it is desired to remove an external device such as a USB key drive; should such device be removed before the filesystem on it is properly unmounted, it is possible that any data recently added to it might not be saved.
The basic syntax of umount is
umount is most commonly used without any of its several options. The filesystem is identified by the full pathname of the directory in which it has been mounted, not by its type. Thus, for example, to unmount a filesystem that is mounted in a directory called /dir1, all that would be necessary is to type in the following at the keyboard and press the Enter key:
Likewise, a USB key device, assuming that it had been mounted in the directory /mnt/usb, would be unmounted with the following:
Attempts to unmount a filesystem are not always successful. The most common problem is that the filesystem is busy. That is, it is currently being used by some process (i.e., instance of a program in execution). In such case an error message such as umount: /dir1: device is busy will be displayed on the screen. This busy state could be the result of something as simple as an GUI window being open that shows an icon of the directory containing the filesystem, in which case it can be easily solved by closing the window. Or it could be the result of a file on that filesystem being open, in which case all that is necessary is to close the file. In less obvious cases, it may be necessary to use a command such as ps or pstree to try to locate the offending process(es) and then use a command such as kill to terminate such process(es).
Another cause of failure is when a user attempts to unmount a filesystem that has already been unmounted. In such case an error message such as umount: /dir1: not mounted will be returned.
In the event that the unmounting is successful, umount usually works silently; that is, there is no message on the screen to confirm its success. However, umount can be made to provide such a message by using the -v (i.e., verbose) option. (This should not be confused with the -V option, which merely returns information about the currently installed version of umount.)
umount allows the name of the physical device on which the filesystem is mounted to be included in the command if desired. This is convenient because it can minimize typing by allowing the user to utilize the upward pointing arrow on the keyboard to display the command that was previously used to mount that filesystem (i.e., to use the history command) and then merely insert the letter u before the word mount and press the Enter key in order to unmount the filesystem. Thus, for example, if a filesystem that is physically located on the second partition of the first HDD (which is designated by dev/hda2) is mounted in a directory called /dir2, it can be unmounted with either of the following:
Interestingly, when the physical device is included, a confirmation message is automatically supplied.
There are several options that can be tried in the event that umount refuses to unmount a filesystem for no immediately apparent reason. Perhaps the most useful is the -l (i.e., lazy) option, which immediately detaches the filesystem from the main filesystem and then cleans up all references to the unmounted filesystem as soon as it is no longer busy. This capability requires Linux kernel 2.4.11 or later.
Another way to deal with an unmounting failure is to use the -r option, which remounts the filesystem as read-only. This presumably allows devices or media to be removed without affecting data which has just been written to them. In addition, the -f option forces unmounting in the case of an unreachable NFS (network filesystem) filesystem.
The -a option causes all of the filesystems described in /etc/mtab to be unmounted. (However, with umount version 2.7 and later the proc filesystem is not unmounted.) /etc/mtab is a file that is similar to /etc/fstab and which is updated by mount and umount whenever filesystems are mounted or unmounted. The -n option causes unmounting to occur without writing to /etc/mtab.
The -t option followed by the filesystem type indicates that the actions should only be taken on filesystems of that type. Multiple types can be specified in a comma-separated list. This list can be prefixed with the word no to specify filesystem types on which no action should be taken.
The -O options indicate that the actions should only be taken on filesystems with the specified options in /etc/fstab. Multiple option types can be specified in a comma-separated list. Those options for which no action should be taken can be prefixed with no.
umount could have instead been called unmount. This might have simplified things for people who are new to the command line (i.e., text-only operation). However, eliminating unnecessary typing is also a part of the Unix philosophy, and thus the n was not used.
Created September 24, 2007.
Copyright © 2007 The Linux Information Project. All Rights Reserved.
Как монтировать файловые системы в Linux
How to Mount and Unmount File Systems in Linux
В этом руководстве мы рассмотрим основу подключения различных файловых систем, использующие команду mount и umount.
В операционных системах Linux и UNIX вы можете использовать mount команду для подключения (монтирования) файловых систем и съемных устройств, таких как USB-устройства флэш-памяти, к определенной точке монтирования в дереве каталогов.
Команда umount отсоединяет (размонтирует) смонтированную файловую систему от дерева каталогов.
Как составить список установленных файловых систем
При использовании без аргументов mount команда отобразит все подключенные в настоящее время файловые системы:
По умолчанию выходные данные будут включать все файловые системы, включая виртуальные, такие как cgroup, sysfs и другие. Каждая строка содержит информацию об имени устройства, каталоге, к которому подключено устройство, типе файловой системы и опциях монтирования в следующей форме:
Например, чтобы напечатать только разделы ext4, вы бы использовали:
Монтирование файловой системы
Чтобы смонтировать файловую систему в заданном месте (точке монтирования), используйте mount команду в следующей форме:
После подключения файловой системы точка монтирования становится корневым каталогом смонтированной файловой системы.
Например, чтобы смонтировать /dev/sdb1 файловую систему в /mnt/media каталог, который вы используете:
Несколько параметров могут быть предоставлены в виде списка через запятую (не вставляйте пробел после запятой).
Вы можете получить список всех параметров монтирования, набрав man mount в своем терминале.
Монтирование файловой системы с использованием / etc / fstab
Если /etc/fstab содержит информацию о данной файловой системе, mount команда использует значение для другого параметра и параметры монтирования, указанные в fstab файле.
/etc/fstab Файл содержит список записей в следующем виде:
Используйте mount команду в одной из следующих форм для присоединения файловой системы, указанной в /etc/fstab файле:
Монтаж USB-накопителя
В большинстве современных дистрибутивов Linux, таких как Ubuntu, USB-накопители автоматически монтируются при их вставке, но иногда вам может понадобиться подключить диск вручную.
Чтобы вручную подключить USB-устройство, выполните следующие действия:
Создайте точку монтирования:
Предполагая, что USB-накопитель использует /dev/sdd1 устройство, вы можете подключить его к /media/usb каталогу, набрав:
Чтобы найти устройство и тип файловой системы, вы можете использовать любую из следующих команд:
Монтирование файлов ISO
Вы можете смонтировать файл ISO, используя устройство петли, которое является специальным псевдо-устройством, которое делает файл доступным как блочное устройство.
Начните с создания точки монтирования, это может быть любое место, которое вы хотите:
Смонтируйте файл ISO в точку монтирования, введя следующую команду:
Не забудьте заменить /path/to/image.iso путь к файлу ISO.
Монтирование NFS
Для монтирования общего ресурса NFS в вашей системе должен быть установлен клиентский пакет NFS.
Установите клиент NFS в Ubuntu и Debian:
Установите клиент NFS в CentOS и Fedora:
Используйте следующие шаги для монтирования удаленного каталога NFS в вашей системе:
Создайте каталог, который будет служить точкой монтирования для удаленной файловой системы:
Как правило, вы хотите смонтировать удаленный ресурс NFS автоматически при загрузке. Для этого откройте /etc/fstab файл в текстовом редакторе :
Добавьте в файл следующую строку, заменив remote.server:/dir IP-адрес или имя хоста NFS-сервера и экспортированный каталог:
Подключите общий ресурс NFS, выполнив следующую команду:
Демонтаж файловой системы
Чтобы отсоединить смонтированную файловую систему, используйте umount команду, а затем либо каталог, в котором она была смонтирована (точка монтирования), либо имя устройства:
Если файловая система используется, umount команда не сможет отсоединить файловую систему. В этих ситуациях вы можете использовать fuser команду, чтобы узнать, какие процессы обращаются к файловой системе:
Определив процессы, вы можете остановить их и размонтировать файловую систему.
Ленивый демонтаж
Принудительно демонтировать
Как правило, не рекомендуется форсировать размонтирование, так как это может повредить данные в файловой системе.
Вывод
К настоящему времени у вас должно быть хорошее понимание того, как использовать mount команду для присоединения различных файловых систем к вашему дереву каталогов и отсоединения монтирований с помощью umount команды.
Чтобы узнать больше о параметрах mount и umount командах, смотрите соответствующие справочные страницы.