Linux создать файл произвольного размера

Quickly create a large file on a Linux system

How can I quickly create a large file on a Linux (Red Hat Linux) system? dd will do the job, but reading from /dev/zero and writing to the drive can take a long time when you need a file several hundreds of GBs in size for testing. If you need to do that repeatedly, the time really adds up. I don’t care about the contents of the file, I just want it to be created quickly. How can this be done? Using a sparse file won’t work for this. I need the file to be allocated disk space.

Ext4 has much better file allocation performance, since whole blocks of up to 100MB can be allocated at once.

People seem to be grossly ignoring the «sparse file won’t work with this», with their truncate and dd seeks below.

You should have defined what you meant by «for testing». Testing the writing speed of your hard disk? Testing what df will report? Testing an app that does something particular. The answer depends on what you want to test. Anyway I’m a bit late — I see now that it’s been years since your question 🙂

Just in case you are looking for a way to simulate a full partition, like I was, look no further than /dev/full

16 Answers 16

dd from the other answers is a good solution, but it is slow for this purpose. In Linux (and other POSIX systems), we have fallocate , which uses the desired space without having to actually writing to it, works with most modern disk based file systems, very fast:

fallocate -l 10G gentoo_root.img 

Is it possible that dd is internally using that already? If I do ‘dd if=/dev/zero of=zerofile bs=1G count=1’ on a 3.0.0 kernel, the write finishes in 2 seconds, with a write data rate of over 500 megabytes per second. That’s clearly impossible on a 2.5″ laptop harddrive.

This ( fallocate ) will also not work on a Linux ZFS filesystem — github.com/zfsonlinux/zfs/issues/326

In Debian GNU/Linux fallocate is part of the util-linux package. This tool was written by Karel Zak from RedHat and source code can be found here: kernel.org/pub/linux/utils/util-linux

Читайте также:  Менеджер загрузки линукс минт

This is a common question — especially in today’s environment of virtual environments. Unfortunately, the answer is not as straight-forward as one might assume.

dd is the obvious first choice, but dd is essentially a copy and that forces you to write every block of data (thus, initializing the file contents). And that initialization is what takes up so much I/O time. (Want to make it take even longer? Use /dev/random instead of /dev/zero! Then you’ll use CPU as well as I/O time!) In the end though, dd is a poor choice (though essentially the default used by the VM «create» GUIs). E.g:

dd if=/dev/zero of=./gentoo_root.img bs=4k iflag=fullblock,count_bytes count=10G 

truncate is another choice — and is likely the fastest. But that is because it creates a «sparse file». Essentially, a sparse file is a section of disk that has a lot of the same data, and the underlying filesystem «cheats» by not really storing all of the data, but just «pretending» that it’s all there. Thus, when you use truncate to create a 20 GB drive for your VM, the filesystem doesn’t actually allocate 20 GB, but it cheats and says that there are 20 GB of zeros there, even though as little as one track on the disk may actually (really) be in use. E.g.:

 truncate -s 10G gentoo_root.img 

fallocate is the final — and bestchoice for use with VM disk allocation, because it essentially «reserves» (or «allocates» all of the space you’re seeking, but it doesn’t bother to write anything. So, when you use fallocate to create a 20 GB virtual drive space, you really do get a 20 GB file (not a «sparse file», and you won’t have bothered to write anything to it — which means virtually anything could be in there — kind of like a brand new disk!) E.g.:

fallocate -l 10G gentoo_root.img 

Источник

6 способов создать файл в Linux определенного размера

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

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

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

Я собираюсь создать файл 10M.

Это можно сделать с помощью следующих 6 методов.

  • fallocate: fallocate используется для предварительного выделения или освобождения места в файле.
  • truncate: truncate используется для сокращения или расширения размера файла до указанного размера.
  • dd: может копировать файл, конвертировать и форматировать в соответствии с операндами.
  • head: head используется для отображения первой части файлов.
  • Команда xfs_mkfile: xfs_mkfile позволяет нам создавать файлы определенного размера в Linux.
  • perl: Perl – это язык программирования, специально разработанный для редактирования текста.
Читайте также:  Как установить openjdk linux

Как создать файл определенного размера в Linux с помощью команды fallocate?

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

Для файловых систем, которые поддерживают системный вызов fallocate, предварительное распределение выполняется быстро, выделяя блоки и помечая их как неинициализированные, не требуя ввода-вывода для блоков данных.

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

$ fallocate -l 10M daygeek.txt

Используйте команду ls, чтобы проверить заданный размер файла.

$ ls -lh daygeek.txt -rw-rw-r-- 1 daygeek daygeek 10M Feb 3 13:43 daygeek.txt

Как создать файл определенного размера в Linux с помощью команды truncate?

truncate используется для уменьшения или расширения размера файла до указанного размера.

$ truncate -s 10M daygeek1.txt

Используйте команду ls, чтобы проверить заданный размер файла.

$ ls -lh daygeek1.txt -rw-rw-r-- 1 daygeek daygeek 10M Feb 3 13:44 daygeek1.txt

Как создать файл определенного размера в Linux с помощью команды dd?

Команда dd означает дубликатор данных.

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

$ dd if=/dev/zero of=daygeek2.txt bs=10M count=1 or $ dd if=/dev/zero of=daygeek3.txt bs=1M count=10 1+0 records in 1+0 records out 10485760 bytes (10 MB, 10 MiB) copied, 0.03385 s, 310 MB/s

Используйте команду ls, чтобы проверить заданный размер файла.

$ ls -lh daygeek2.txt -rw-rw-r-- 1 daygeek daygeek 10M Feb 3 13:44 daygeek2.txt

Как создать файл определенного размера в Linux с помощью команды head?

Команда head считывает первые несколько строк любого текста, переданного ему в качестве ввода, и записывает их в стандартный вывод (который по умолчанию является экраном дисплея).

$ head -c 10MB /dev/zero > daygeek4.txt

Используйте команду ls, чтобы проверить заданный размер файла.

$ ls -lh daygeek4.txt -rw-rw-r-- 1 daygeek daygeek 9.6M Feb 3 13:45 daygeek4.txt

Как создать файл определенного размера в Linux с помощью команды xfs_mkfile?

xfs_mkfile создает один или несколько файлов. Файл дополняется нулями по умолчанию.

Размер по умолчанию – в байтах, но его можно пометить как килобайты, блоки, мегабайты или гигабайты с суффиксами k, b, m или g соответственно.

$ xfs_mkfile 10M daygeek5.txt

Используйте команду ls, чтобы проверить заданный размер файла.

$ 1 ls -lh daygeek5.txt -rw------- 1 daygeek daygeek 10M Feb 3 13:45 daygeek5.txt

Как создать файл определенного размера в Linux с помощью команды perl?

Perl означает «Practical Extraction and Reporting Language».

Perl – это язык программирования, специально разработанный для редактирования текста.

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

$ perl -e 'print "a" x 10485760' > daygeek6.txt

Используйте команду ls, чтобы проверить заданный размер файла.

$ ls -lh daygeek6.txt -rw-rw-r-- 1 daygeek daygeek 10M Feb 3 13:47 daygeek6.txt

Все вместе в одном выводе.

$ ls -lh daygeek* -rw-rw-r-- 1 daygeek daygeek 10M Feb 3 13:44 daygeek1.txt -rw-rw-r-- 1 daygeek daygeek 10M Feb 3 13:44 daygeek2.txt -rw-rw-r-- 1 daygeek daygeek 10M Feb 3 13:44 daygeek3.txt -rw-rw-r-- 1 daygeek daygeek 9.6M Feb 3 13:45 daygeek4.txt -rw------- 1 daygeek daygeek 10M Feb 3 13:45 daygeek5.txt -rw-rw-r-- 1 daygeek daygeek 10M Feb 3 13:47 daygeek6.txt -rw-rw-r-- 1 daygeek daygeek 10M Feb 3 13:43 daygeek.txt

Источник

Читайте также:  Включить wake on lan linux

How can I create a file with a specific size from a command line?

How can I create a file (e.g. using the touch command or another similar way), but with a specific size (e.g. 14 MB)? The use case is to test FTP with various file sizes. If we can create a file with a specific size, it will be useful to verify FTP transfer etc.

7 Answers 7

DESCRIPTION Shrink or extend the size of each FILE to the specified size [. ] -s, --size=SIZE set or adjust the file size by SIZE 

Note: truncate may not be available on your system, e.g. on Mac OS X it’s not installed by default (but you can easily install it, using macports for example). In these cases you may need to use dd or head instead.

Very nice indeed. The touch is not needed though, you can simply run truncate -s 14M filename it will create filename directly.

This seems to create a sparse file, whereas the below answer (that uses «dd») doesn’t. I don’t know if the difference is important to you, but I figured I’d point it out

EDIT: The simplest way is probably the truncate of Ashutosh Vishwa Bandhu’s answer, but as pointed out by @offby1 that creates sparse files which may not be what you want. The solutions below create normal, full files.

The following commands create a 14MB file called foo :

    fallocate (thanks to @Breakthrough who suggested it in the comments and vote up Ahmed Masud’s answer below which also mentions it.)

This command is particularly impressive since it is as fast as truncate (instantaneous) irrespective of the desired file size (unlike the other solutions which will be slow for large files) and yet creates normal files, not sparse ones :

$ truncate -s 14MB foo1.txt $ fallocate -l 14000000 foo2.txt $ ls -ls foo?.txt 0 -rw-r--r-- 1 terdon terdon 14000000 Jun 21 03:54 foo1.txt 13672 -rw-r--r-- 1 terdon terdon 14000000 Jun 21 03:55 foo2.txt 
dd if=/dev/urandom of=foo bs=14MB count=1 
head -c 14MB /dev/urandom > foo 
dd if=/dev/zero of=foo.txt bs=14MB count=1 

In all of the above examples, the file will be 14*1000*1000 if you want 14*1024*1024 , replace MB with M . For example:

dd if=/dev/urandom of=foo bs=14M count=1 head -c 14M /dev/zero > foo 

fallocate only deals in bytes, so you’d have to do (14*1024*1024=14680064)

Источник

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