How to mount usb drive linux
How to mount usb drive linux
How to mount usb drive in a linux system
Do you know “how to use USB memory sticks with Linux”, If you are not sure then this article describes “how to mount USB drive on a Linux system with command line interface”
Universal serial bus, or USB (also known as Flash drive), is an electronic communications protocol that is commonly used in computer accessories and other small devices. If you have an up-to-date Linux system and a modern Desktop environment, your device should show up on your desktop, with no need to open a console. There are few important factors which are involved in learning how to mount USB drive with Linux machine.
Following are the step by step instructions to understand further –
Step 1: Plug-in USB drive to your PC
Step 2 – Detecting USB Drive
After you plug in your USB device to your Linux system USB port, It will add new block device into /dev/ directory. To verify it, use the following command –
The sample output should be like this –
We can observe from the above result that, device boot, blocks, id and system format are displayed.
Step 3 – Creating Mount Point
To mount the USB, use the following command –
To create a directory in the mounted device, use the following commands –
The above command creates a directory called john in USB device.
Step 4 – Delete a Directory in USB
To delete a directory in USB, use the following command –
Step 5 – Formatting the USB
You should unmount the device first to format the USB device, then use the following command to unmount the device –
Now use either of the commands as per file system based on your requirement. To format a USB drive, users generally prefer VFAT or NTFS file systems because they can be easily mounted on Windows operating systems and Linux systems.
Format vs Fat FileSystem
To format USB with vFat File System, use the following command –
Format NTFS FileSystem
To format a USB Flash Drive with NTFS file system, use the following command –
Format EXT4 FileSystem
To format a USB with EXT4 file system, use the following command –
Congratulations! Now, you know “How to Mount USB Drive in a Linux System?”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
Как примонтировать флешку в Linux
В наши дни очень большую популярность у пользователей набрали USB флешки. Они используются для обмена файлами, различными фильмами и документами, установки операционных систем, а также восстановления системы после сбоя. Чтобы работать с флешкой в Linux ее нужно примонтировать в корневую файловую систему.
Дело в том, что организация файловой системы Linux немного отличается от того, что мы привыкли видеть в Winodws. Здесь нет никаких дисков C,D,E и так далее, есть только корень, самая верхняя точка файловой системы, в подкаталоги которой подключаются все жесткие диски и внешние носители.
Если в системе используется окружение рабочего стола, то оно, как правило, берет на себя всю низкоуровневую работу чтобы выполнить монтирование флешки в linux. Система обнаруживает подключенную флешку и в системном лотке всплывает уведомление о подключенном устройстве. Дальше остается кликнуть по значку флешки, чтобы система выполнила все нужные для ее монитрования действия. Но если окружение рабочего стола не запущенно или вам нужно работать в консоли можно выполнить все действия по монтированию флешки вручную.
В этой инструкции мы рассмотрим монтирование usb флешки в linux через терминал, а также настройку автоматического монтирования для оконных менеджеров, которые не поддерживают такую возможность.
Монтирование флешки в Linux
Файлы флешек и других устройств хранения данных находятся в каталоге /dev. Устройства нумеруются по алфавиту sda, sdb, sdc, sdd и т д. Так как флешка подключается последней у нее будет старшая буква. Например, sdb или sdc. Имя sda принадлежит жесткому диску. Можно, конечно, просто посмотреть содержимое каталога /dev/, но такой способ ненадежный. Мы воспользуемся утилитой fdisk.
Подключите флешку и выполните:
Как видите, здесь мы можем посмотреть детальную информацию об устройстве. Имя файла, список разделов, формат таблицы разделов, список разделов. А главное для нас, размер раздела и его файловую систему. Теперь не сложно понять какая из них флешка. В этом примере это /dev/sdc1
Создаем папку для монтирования:
sudo mkdir /mnt/usb
Теперь монтируем флешку с помощью команды mount:
sudo mount /dev/sdc1 /mnt/usb
Монтирование осуществляется от суперпользователя, но если нужно чтобы отмонитровать флешку мог любой нужно указать опцию users:
По умолчанию владельцем файлов на флешке при монтировании устанавливается root, поэтому если вы захотите работать с флешкой через файловый менеджер, то нужно будет его запускать с правами суперпользователя или же сразу примонтировать флешку в linux таким образом, чтобы владельцем был ваш пользователь. Для этого укажите группу и id своего пользователя в опциях uid и gid:
Удостовериться что флешка подключена можно посмотрев содержимое каталога, в который мы ее монтировали:
Или выполнив команду mount:
После завершения работы с флешкой не забудьте ее отмонтировать. Потому что иначе данные могут быть не сохранны или вообще повреждена файловая система флешки:
sudo umount /dev/sdc1
Автоматическое монтирование флешки в Linux
Популярные окружения рабочего стола выполняют монтирование флешки linux автоматически, как только она подключена к системе или по клику на ярлыке. Мы можем это реализовать с помощью службы udisks2.
Мы тоже можем использовать его для ручного монтирования. Здесь даже есть несколько плюсов. Во-первых, мы можем монтировать без прав суперпользователя, во-вторых, не нужно создавать папку.
Для монтирования используется такая команда:
Для размонтирования используется аналогичная команда:
Автоматическое монтирование usb флешки в linux можно настроить с помощью утилиты udiskie. Все новые подключенные флешки будут автоматически подключаться, после подключения устройства будет всплывать окно с предложением открыть файловый менеджер, а также значок, с помощью которого можно получить доступ к каждому из устройств.
Устанавливается утилита в Ubuntu командой:
sudo apt install udiskie
Дальше остается запустить программу:
Теперь все подключаемые устройства будут автоматически монтироваться с помощью udisks. Рассмотрим что значат опции:
Выводы
Теперь монтирование флешки linux не вызовет у вас проблем. Даже если у вас не будет работать окружение рабочего стола и придется делать все вручную. Если остались еще вопросы, спрашивайте в комментариях.
Solved: How to Mount USB Drive in Linux [100% Working]
Table of Contents
If you have a usb disk and you are thinking «how to mount USB drive in Linux», you should read this article.
Required RPM to mount USB Drive in Linux
First of all, if you are using a Linux with a graphical interface (KDE, Gnome, XFCE etc.), most Linux distributions do the usb disk connection work for you. Sometimes, extra package installation may be required for this.
You can find the answer to the question «Which packages should I install for the disk format» in the picture below.
In addition, the installed package also has operations on the usb disk. For example, you can see if you can perform operations such as create, share and copy after package installation.
Install Required Packages
USB with NTFS File System
For a usb disk with ntfs file type, ntfs-3g or ntfsprogs packages must be installed on the system.
If you are using a Debian based distribution (Ubuntu, Debian, Pardus etc.) and to confirm that this package is installed;
The above command will show package and its version if installed.
If you want to install this package, use following command:
If you are using a RedHat based distribution (CentOS, Rocky Linux, Alma Linux or Fedora);
you can check the existence of the package in the system with this command. For installation, run the following command on the terminal.
USB with FAT32 File System
If you have a USB disk with FAT32 file type, the dosfstools package must be installed in the system.
To install on Debian-based distributions;
and to install on Redhat-based distributions
How to identify the USB drive in Linux?
You have connected your USB to the Linux box but you are not sure how to identify the partition name of the USB? There are many commands which you can use to easily identify the connected USB drive.
Here I have consolidated Linux mount command to access filesystems, iso image, usb, network drives, refer this article for more details
The lsblk command will list the disks inserted into the Linux server:
Your disk should show on this screen with its size. If not, plug the disk into a different usb port. If still no results, try connecting the USB disk to another computer. If there is no physical problem with the disk, it will definitely show on this screen.
For all information about the disk;
you can run the command. Command output;
will display some information about the device.
How to get the File System type of USB Drive?
We can use blkid command which will show the file system type of the USB Drive.
For example for USB Drive with NTF File System type:
Similarly for a USB drive with FAT32 File System type:
Steps to mount USB Drive in Linux
After confirming that the disk does not have a physical problem, if you know the format of your disk, you can follow the mount steps.
Step-1: Create Mount Point
Create the directory where you will mount the disk with the following command. This is optional step and if you intend to temporarily mount the USB drive then you can just mount it on /mnt
With this command you can confirm that the directory has been created.
Step-2: Mount the USB drive to mount point
It is important to mount the USB Drive to some partition to be able to access the content of the drive. So we will mount our USB drive i.e. /dev/sdb1 to /media/my_disk
Step-3: Verify
After the command is executed, the USB disk is connected to the system. You can verify the same using:
If you have inserted a FAT32 disk, the output will be as follows;
You can also verify the same using lsblk command output after mounting steps;
Changing File System type of USB Drive using mkfs
Operations such as file copy speed may cause problems due to the format of your current disk. For example, USB drive cannot save a single file larger than four GB by default due to the limitation in the FAT32 file system. Therefore, it is necessary to convert your FAT disk to exFAT or NTFS format.
First unmount the USB drive using umount command:
The mkfs command is used in Linux for formatting. For example, in the terminal to make the file system of your usb disk exfat;
Or if you want to format it as NTFS due to its unique features (journaling, fake copy etc.);
How to unmount USB Drive in Linux
First of all, verify that the USB disk is connected to the system;
Next execute the umount command followed by the USB partition OR mount point as we identified in previous commands;
Now we can safely delete the temporary mount point which we created:
If you attempt to delete the my_disk directory without unmounting, then you will get below error. So, first perform the umount operation and then the directory deletion.
If you get «target is busy» during the umount process as shown below, it means that the USB disk is still in use. In such event you can either try to forcefully unmount the device or you must exit this directory in terminal or graphical interface which is using USB drive. Then repeat the umount process.
Permanently mount USB Drive using FSTAB
The operations in the above steps are one-time binding steps. When the computer restarts, your disk will not be mounted, you will have to repeat the mount steps you did before.
Get the UUID of the USB Drive, it is always recommended to use UUID instead of partition name as the partition name is prone to change if some other disk/storage gets mounted before the USB. In such case the mount operation will fail leading to boot up issues.
Execute blkid command to get the UUID of your USB drive:
Now update the /etc/fstab file with a new entry and provide disk, path to be mounted, disk format, connection priority and permissions.
WARNING: Operations on the /etc/fstab directory may cause the operating system not to boot after reboot. Therefore, it is important to have a backup before starting. At the terminal;
Take the backup without any operation with the command. In a negative situation, you can restore the system by returning from this backup.
For permanent mount operation;
The script opens the file. Add the following to the last line of the file;
For FAT32 format;
For exFAT format;
Then save and exit with the CTRL + X command.
Finally
We recommend that you look at the man pages for the mount and mkfs commands. For this, in the terminal;
just run the commands. The information and parameters on these pages are the most accurate sources.
Before formatting the disk, make sure that you do not have any important data in the disk. Most importantly, make sure to format the USB disk during disk formatting. Otherwise, you may be formatting the system disk.
Related Posts
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Ubuntu Documentation
Introduction
This page explains how to use USB drives, like external hard disks and USB flash drives (aka USB sticks, thumb drives, pen drives, etc). The material here also applies to flash cards (like in your digital camera).
USB storage devices have the enormous advantage that for the most part they use a standard set of protocols. Thus, instead of needing individual drivers, as does much computer hardware, a standard driver permits access to the devices, making them very portable and able to easily work on many platforms.
For help with internal hard drives, see Fstab and MountingWindowsPartitions.
Automounting
Mounting
By default, storage devices that are plugged into the system mount automatically in the /media/ directory, open a file browser window for each volume and place an icon on your desktop. The rationale for this slight change of behavior can be found here. If you plug in a usb hard disk with many partitions, all of the partitions will automatically mount. This behaviour may not be what you want; you can configure it as shown below.
If the volumes have labels the icons will be named accordingly. Otherwise, they will be named «disk», «disk-1» and so on.
To change the volume label see RenameUSBDrive.
Configuring Automounting
To enable or disable automount open a terminal and type:
Browse to org.gnome.desktop.media-handling.
The automount key controls whether to automatically mount media. If set to true, Nautilus will automatically mount media such as user-visible hard disks and removable media on start-up and media insertion.
Another key, org.gnome.desktop.media-handling.automount-open, controls whether to automatically open a folder for automounted media.
If set to true, Nautilus will automatically open a folder when media is automounted. This only applies to media where no known x-content type was detected; for media where a known x-content type is detected, the user configurable action will be taken instead. This can be configured as shown below.
Configuring Program Autostart
For more complex scenarios, see UsbDriveDoSomethingHowto.
Unmounting/Ejecting
Auto-mounting (Ubuntu Server)
By default, disk drives do not auto-mount in Ubuntu Server Edition. If you are looking for a lightweight solution that does not depend on HAL/DBUS, you can install «usbmount».
Manually Mounting
Using Disks
Disks (the GNOME disk utility) is an application for visually managing disk drives and media. When you run it, you will see a list of your drives, including USB drives. If you click a drive on the list, you can view its details, and you can click the triangle-shaped button (Play button) to mount the drive. (This method works even when the drive does not auto-mount.)
Using mount
Get the Information
Sometimes, devices don’t automount, in which case you should try to manually mount them. First, you must know what device you are dealing with and what filesystem it is formatted with. Most flash drives are FAT16 or FAT32 and most external hard disks are NTFS. Type the following:
Find your device in the list. It is probably something like /dev/sdb1. For more information about filesystems, see LinuxFilesystemsExplained.
Create the Mount Point
Now we need to create a mount point for the device. Let’s say we want to call it «external». You can call it whatever you want, but if you use spaces in the name it gets a little more complicated. Instead, use an underscore to separate words (like «my_external»). Create the mount point:
Mount the Drive
We can now mount the drive. Let’s say the device is /dev/sdb1, the filesystem is FAT16 or FAT32 (like it is for most USB flash drives), and we want to mount it at /media/external (having already created the mount point):
The options following the «-o» give you ownership of the drive, and the masks allow for extra security for file system permissions. If you don’t use those extra options you may not be able to read and write the drive with your regular username.
Otherwise, if the device is formatted with NTFS, run:
Note: You must have the ntfs-3g driver installed. See MountingWindowsPartitions for more information.
Unmounting the Drive
When you are finished with the device, don’t forget to unmount the drive before disconnecting it. Assuming /dev/sdb1 is mounted at /media/external, you can either unmount using the device or the mount point:
You cannot unmount from the desktop by right-clicking the icon if the drive was manually mounted.
Using pmount
There is a program called pmount available in the repositories which allows unprivileged users to mount drives as if they were using sudo, even without an entry in /etc/fstab. This is perfect for computers that have users without RootSudo access, like public terminals or thin clients.
pmount can be used with the same syntax as mount (but without sudo), or quite simply as follows:
If you leave off the label option, it will mount by default at /media/device.
To unmount the device, use pumount, like so:
For more help, see the man pages for pmount and pumount.
The Importance of Unmounting
Before disconnecting devices, you must unmount them first. This is similar to «Safely Remove» in Windows in that the device won’t unmount until data is finished being written to the device, or until other programs are finished using it. This applies to all types of storage devices, including flash drives, flash cards, external hard drives, ipods and other media players, and even remote storage like Samba or NFS shares.
Other Useful Commands
To see a list of your USB devices (the vendor and device ID’s), run:
To see all attached storage devices and their partitions, run:
To see information about currently mounted systems, simply run:
Troubleshooting
Presented here are some common problems users encounter.
Interfering services
Two services/programs responsible for automounting might interfere and thereby prevent a successful automount and permission setting.
Example: Activating the Automount function of Nautilus while using pmount will result in read-only permissions for normal users. Either disable Nautilus’ Automount function or deinstall pmount.
Unclean LogFile
If you are mounting drives formatted with NTFS (like most external USB hard disks are), you must first have the ntfs-3g driver installed. This is done automatically in newer versions of Ubuntu. You should also install ntfs-config and enable mounting, which is not done automatically. For ntfs-3g and ntfs-config, see MountingWindowsPartitions.
When a drive is not Safely Removed from a Windows machine (or a forced shutdown occurs from Windows), you may get an error like this when you plug in your drive:
The best option is Choice 1, but you can force the mount by running Choice 2 with sudo. You must then manually unmount it from the terminal (you can’t right click the desktop icon):
After that the drive should automount normally again.
User Privileges
If your usb device doesn’t appear on your desktop, you should check that your user has the correct privileges. Go to System->Administration->User and Groups, choose the user, click on «Properties», then go to the «User Privileges» tab. You should have the «Access external storage devices automatically» option checked.
Preferences
If your usb device doesn’t appear on your desktop, you should check that the automount action is enabled in the preferences:
NOTE: This does not seem to apply to Hardy Heron.
USB 2 Issues
old kernels workaround
If you encounter problems using your USB device with USB 2 (i.e. ‘high speed’ mode), you can revert to the ‘full speed’ mode (slower) by unloading ehci_hcd. To do that, type in a terminal:
before plugging in your device.
recent kernels workaround, from Karmic
Buffer I/O Errors
If you see errors related to Buffer I/O when attaching a USB storage device, there are two ways to work around it. First, try using varying max_sectors settings, as such:
Try values of 120, 64 and 32.
If this does not resolve the issue, then you may need an unusual_dev entry for your device. It would look something like this:
The vendor and device IDs can be obtained from the output of «lsusb». The entry would be placed in drivers/usb/storage/unusual_devs.h. If you cannot compile your own kernel, please file a bug report, and we’ll attempt to compile a test module for you.
Device suddenly becomes read-only
If your device changes suddenly to read-only mode, and you see this kind of error:
This might be the sign of an unclean device. You should check your device. Try TestingStorageMedia to do so. Or use «Disk Utility» (under System, Administration), find your device, unmount it, check the file system, then mount it again.
USB-Device is or becomes read-only without errors
If you see «Write Protect is off» and no errors in your logfiles, than you should set filesystem type specific mount options (FS_MOUNTOPTIONS) in /etc/usbmount/usbmount.conf. Wrong gid causes mounting read only.
General tip
When you encounter problems with USB devices, the first thing to do is to check the latest debug information generated from the kernel just after you plug in your device and/or just after you encounter the problem.
To do that, open a terminal and type :
Check the latest messages; they should be related to your problem.
Seeking Further Help
The best place to get help with almost any Ubuntu problem is on the Ubuntu Forums. The Absolute Beginner Talk section is best for beginners.
Other Resources
Some other related material:
How to Mount USB Drive on Linux
These days, it’s quite common to see people carrying their data around at all times. Different devices and technologies are used for this purpose, including a certain device called USB (Universal Serial Bus).
A USB is an electronic communication protocol (ECP) most commonly used for computer accessories and other small-end electronic devices, either for data transfer or power transfer. Although USBs are being phased out slowly due to technologies such as “Cloud Computing”, there is a sense of privacy and security with using USBs that you don’t get with other methods.
Accessing USBs is straightforward. It is a plug-and-use device, so the stick only needs to be connected to your computer via a USB port. Usually, USBs mount themselves automatically to your system regardless of the operating system, but there are instances where there is a problem, and the USB refuses to connect.
For such times, if you are using a Linux distro, it is best to use the Terminal and execute your way to mount the USB in your computer. This article will be guiding you on how exactly you can achieve this task.
Although it is time-consuming, once you know how to mount a USB in Linux, you will feel lightened, and it will be easier for you to perform it the next time when needed. So follow these instructions to get a proper hang of it.
1) Plugin Your USB Drive into Your PC
First, you need to plug in your USB drive to your Linux-based personal computer (PC), in which you want to access the USB drive.
2) Detecting the USB Drive on Your PC
The second step is the most important and easy step to accomplish. After plugging in your USB to your computer, the system will add a new block device into the /dev/ directory. To check that, use the following command. But first, open your Command Terminal and then type the following command:
The resulting screen should be seen with an output like this:
The result above shows that device boot, blocks, id, and system format are displayed. After this step, you need to create a mount point.
3) Create a Mount Point
For creating a mount point, just type the following command:
In the command mentioned above, “sbd1” refers to the name of your USB Device.
4) Creating a Directory in the USB Drive
We move on to the next step. In this step, you must create a directory in the mounted device. For that, use the following command:
The above commands will create a directory named “John” in the USB Drive. You can create the directory of your desired name by replacing it with John. For example.
This command will create a directory in the USB Drive with the name “Google”. After completing this step, you have now successfully mounted the USB drive in your Linux system.
5) Delete a Directory in USB Drive
After learning about creating a Directory on your USB, it’s time to learn about how you can delete a directory on your USB Drive. To delete a directory, write the following command.
The above-mentioned command will delete the drive named as “John”. But if you want to delete a directory with your desired name, just replace it with “John”. For example.
The above code deletes the directory named “Google”. Similarly, you can write any of your desired names to delete a directory on your USB Drive on a Linux-operated computer.
6) Formatting the Mounted USB in Linux
In order to format a USB Flash Drive, you need to unmount the drive first. Use the following command to unmount the USB.
In the aforementioned command, “sbd1” refers to the name of your USB Device. Next, you have to choose either of the following codes as per your USB Drive file systems:
For VFAT (FAT32) File System
To format VFAT (FAT32) file system, use:
In the command mentioned above, “sbd1” refers to the name of your USB Device.
For NTFS File System
To format NTFS file system USB Drive, use:
For EXT4 File System
For formatting EXT4 file system USB Drive, use:
Conclusion
This guide covered how to mount a USB drive in your Linux system. It also described the commands you can use to delete directories or format your USB device. We hope that we can help you out and that you can use your USB with your Linux without any problems.
About the author
Zeeman Memon
Hi there! I’m a Software Engineer who loves to write about tech. You can reach out to me on LinkedIn.