[Mac OS X] Делаем установочный USB-диск OS X Lion из командной строки
В прошлой заметке, мы рассмотрели, как средствами командной строки записать установочный DVD-диск OS X Lion. Некоторые читатели отметили, что неплохо бы было узнать, как сделать то же самое, но для USB-диска. И действительно, не оставлять же владельцев MacBook Air и последних Mac mini обделенными. 🙂
Приступим. Сразу оговорюсь, что для успешного создания установочного диска нам потребуется дискового пространства на USB-диске немного больше 4GB, а потому для этих целей годятся флешки с объемом более 4GB, например, на 8GB. В моем примере используется флешка на 16GB.
Подключаем флешку к компьютеру. Сначала нам нужно определить, в качестве какого устройства подключенный диск известен системе. Для этого открываем Терминал.app и вводим следующую команду:
Будет выведена информация обо всех известных системе дисках. Выглядит это примерно так (все картинки кликабельны):
Из выведенной по этой команде информации, нам необходимо понять, что к чему относится. В принципе понять это не сложно. Устройство /dev/disk0 — ваш локальный диск, с установленной OS X. А нужная нам информация, относящаяся к нашей флешке, выделена на картинке красным. В моем случае (да и в вашем скорее всего) это /dev/disk1 .
Теперь нам нужно создать диск с GPT-разметкой, с одним разделом и файловой системой HFS+. Это делается следующей командой:
diskutil partitionDisk /dev/disk1 1 GPTFormat HFS+ Lion 16G
Где /dev/disk1 — то, что было выделено красным на картинке выше, 1 — создаем один раздел, GPTFormat — указание создать GPT-разметку на диске, HFS+ — файловая система для создаваемого раздела, Lion — метка раздела (может быть произвольной), 16G — размер создаваемого раздела (должен соответствовать размеру вашей флешки, исправьте если нужно).
В результате получится примерно так:
Как видите, на самом деле, на нашем диске было создано два раздела, а не один. Первый раздел с идентификатором disk1s1 — системный раздел EFI размером около двухсот мегабайт, не обращайте на него внимания. Нам нужен второй (большой) раздел с идентификатором disk1s2 (на картинке выделен красным).
Именно этот идентификатор (а точнее его полный вариант записи /dev/disk1s2 ) нам и понадобится для следующей завершающей команды, которая и создаст установочный диск:
asr restore —source /Applications/Install\ Mac\ OS\ X\ Lion.app/Contents/SharedSupport/InstallESD.dmg —target /dev/disk1s2 —erase —noprompt
Еще раз обращаю ваше внимание, что в этой команде мы используем идентификатор диска /dev/disk1s2 (выделен красным).
По завершению работы команды мы и получим, то, чего добивались — установочный USB-диск OS X Lion.
Новости, статьи и анонсы публикаций
Свободное общение и обсуждение материалов
Лонгриды для вас
Почему-то всегда было принято считать, что iOS неважен объём оперативной памяти. Поэтому, когда аппараты на Android имели уже по 2 ГБ, в Купертино по-прежнему ограничивалась 512 МБ. Не то чтобы владельцам iPhone не хотелось большего, но поскольку никаких проблем в работе даже не самых новых аппаратов не было, пользователи практически не возмущались. Более того, находились […]
Конференция с коллегами по работе в Zoom, прямой эфир в Instagram, ваша жена, которая смотрит YouTube, ведущие на телевидении, которые каждый день рассказывают новости, причем многие также делают репортажи из дома. Что у всех у них общего? Правильно — все участники этих событий носят AirPods. Неважно, будь это AirPods Pro или обычные, наушники Apple во […]
Запуск iPhone SE 2020, как мне показалось, был воспринят пользователями слишком оптимистично. Это и понятно – новинку ждали целых три года, тем более что сейчас она явно должна быть более востребованной, чем оригинальная модель. Ведь тогда самый дорогой iPhone стоил 749 долларов, в сегодня – на 300 долларов больше. Вот только стоит ли рубить сплеча […]
Question: Q: Please help diskutil partitionDisk for Fat doesn’t work syntax nowhere to be found.
I am trying to format a flash drive with fat32, this is beyond frustrating, no syntax examples anywhere and all articles online just have the man page.
i run this; diskutil partitionDisk /dev/disk2 MBR JHFS+ untitled 0b
then I try to change it as FAT32 and continually get a syntax fail.
PLEASE SOMEONE SHOW ME HOW TO DO diskutil partitionDisk MBRFormat «MS-DOS FAT32»
what the **** is going on I want 1 partition filling the entire disk, mbr, fat32, why so **** difficult?
please save me before I hit myself.
OS X Yosemite (10.10.5)
Posted on Sep 8, 2015 4:00 AM
All replies
Loading page content
Page content loaded
I am trying to format a flash drive with fat32, this is beyond frustrating, no syntax examples anywhere and all articles online just have the man page.
Here’s the important part you seem to be missing:
For each partition, a triplet of the desired file system format, vol-
ume name, and size must be specified. … The triplets must be as follows:
o Format names are of the form jhfs+, HFS+, MS-DOS, etc.; a
list of formattable file systems (more precisely, specific
file system personalities exported by the installed file
system bundles) and common aliases is available from the
listFilesystems verb.
Following the instructions, this works:
diskutil partitionDisk disk8 MBR fat32 «NO NAME» 100%
Note that in your example, you didn’t complete the triplet, i.e. volume name and the size. You can use a percentage as the size as I did above.
diskutil partitionDisk disk8 MBR «MS-DOS FAT32» «NO NAME» 100%
Also, the quotes are only necessary if you have spaces in the format or name
Как отформатировать носитель из Терминала на Mac
Иногда может потребоваться отформатировать диск с помощью командной строки, а не через графический интерфейс Дисковой утилиты. Дисковая утилита предоставляет много возможностей для управления дисками. Это простой и понятный инструмент для работы с внешними накопителями на Mac.
Тем не менее, функционал графического интерфейса сильно ограничен. Под ним спрятана мощная командная утилита, которая позволяет делать намного больше. Например, Дисковая утилита не даёт разбить диск с таблицей разделов Master Boot Record на разделы, а утилита командной строки даёт.
Команду можно удалённо запустить на десятках компьютеров одновременно или написать скрипт, который за несколько секунд приведет к единому состоянию несколько флешек или внешних дисков.
В то же время использование командной строки требует внимания и точности ввода параметров, чтобы гарантировать, что отформатирован будет именно тот диск и именно в том виде, в котором нужно.
Pro Terminal Commands: Using diskutil
diskutil is the command line version of Disk Utility, the macOS application used to manage hard drives. Just like Disk Utility, you can use the command to format disks, erase drives and more. Once you’re familiar with it, you’ll find that the command is often more powerful and faster than Disk Utility, with more features to boot.
Getting Acquainted with diskutil
If you simply type diskutil into the command line and press Enter, you’ll receive a list of “verbs” that diskutil can operate on.
Just like in the English language, these verbs are things that diskutil can accomplish. The most basic verb for diskutil is list , which you’ll enter like so:
This command will list all the disks attached to your machine. It indicates information like partitions, format and, importantly, mount points. The mount points start with /dev/disk and are used to specify disk operations in diskutil. Partitions (called “volumes” in diskutil parlance) are specified by their identifier on the right.
Disk identifiers follow the format disk_s_, where the underscores are replaced with identifying numbers.
Using verbs
We can use the other verbs to get more information about our drives and run specific operations.
The info verb gets more information about a specific disk (disk1, in this case). Use the mount point to specify the target disk to grab information on. You’ll see tons of stuff you might care about and a lot of stuff you won’t. This is the most information you can get about your disk in one place, and it’s helpful when troubleshooting drive problems.
Unmounting and Ejecting with diskutil
The umount verb unmounts a specified volume. Unmounting is just like ejecting a volume from Finder, but it can be done to internal disks. In this example, I’ve specified the volume I want to unmount with the disk identifier. You can also specify the volume using the partition name. Unmounted disks become inaccessible via Finder, but they can still be seen via diskutil list and manipulated with other diskutil commands. Also, note the command is umount , with no “n”.
The unmountDisk verb is similar to umount , but it unmounts an entire disk instead of one volume. Disks are specified with their mount point, as seen above. You can’t unmount your boot disk or volume, and you’ll get an error if you try to unmount a disk or drive that’s currently in use.
The eject verb is a lot like unmounting a drive, but only for removable disks. Removable disks are things like USB hard drives and flash drives. If it connects through an interface on the outside of your computer, it qualifies as a removable drive. Once a drive is ejected, it won’t appear in Finder or diskutil list until it’s physically unplugged and plugged in to its interface again.
The mount verb is the inverse of the umount verb. It mounts volumes on internal disks manually. Only unmounted volumes can be mounted, obviously. To mount all volumes on a disk, use diskutil mountDisk disk1 , for example.
Fixing Problems with diskutil
The verifyVolume verb will run a verification pass on a specific volume. Verification involves checking the contents of the disk against the expected values. If any mismatches are found, the disk will be identified as in need of repair.
If it turns out that your volume needs to be repaired after you’ve verified it, you can run the repairVolume verb. This will run a repair pass on the volume and attempt to fix any problems found in the verification process.
Format and Erase Drives with diskutil
The eraseDisk verb handles reformatting disks, which erases all data and volumes on a single disk. The verb takes as inputs the format, new disk name and disk identifier, in that order. This example will erase disk2 and reformat it as journaled HFS+. The new disk will have one volume named
The reformat verb will erase a single volume on the disk while keeping the same name and format. It rewrites the same file system that the volume started with, resetting the volume to a blank state.
Partition Drives with diskutil
The partitionDisk verb runs an command-line version of Disk Utility, allowing you to create multiple partitions on a single disk. It’s a little complicated, but it follows this format for it’s arguments:
diskutil partitionDisk MountPoint [numberOfPartitions] [APM|MBR|GPT] [part1Format part1Name part1Size part2Format part2Name part2Size part3Format part3Name part3Size . ]
Partition sizes can be specified in gigabytes with the G suffix (2 G) or terabytes with the T suffix (2 T). My favorite way to specify partition sizes, however, is with percentages (25%, for example). The size of the final partition can be specified with “R” to indicate that it should take up the remainder of the disk.
For example, the following command will create three partitions:
They’ll be formatted with JHFS+, APFS and ExFAT, and named Volume1, Volume2 and Volume3 respectively. Volume1 and Volume2 will each take up 25 percent of the disk, and Volume3 will occupy the remainder. It will also use the GUID Partition Table (GPT) which is one of the more flexible partition table options.
You can see the results of the operation at the end of the Terminal window to determine everything went okay. Using partionDisk isn’t the easiest way to partition a disk, but if Disk Utility is complaining, its a good alternative.