Filename length limits on linux?
See the Wikipedia page about file systems comparison, especially in column Maximum filename length.
Here are some filename length limits in popular file systems:
BTRFS 255 bytes exFAT 255 UTF-16 characters ext2 255 bytes ext3 255 bytes ext3cow 255 bytes ext4 255 bytes FAT32 8.3 (255 UCS-2 code units with VFAT LFNs) NTFS 255 characters XFS 255 bytes
@rahmanisback that’s right for filename limits, while path limits are usually defined by the OS, not FS (except for some strange FSes like iso or ntfs), and, on linux, are 4K
I’m shocked by these limits. Files per directory is unlimited, 4 billion files per volume, file sizes into the terabytes, volume sizes go to exabytes but we have a stupid limit of 255 bytes for file names?
It should also be mentioned that if you layer eCryptFS with filename encryption on top of these file systems (as installed in Ubuntu with encrypted home dir option) the effective maximum filename length will only be 143 characters. See: unix.stackexchange.com/a/32834/47938
I’ve read here that path length limit is in system headers. File name length limit is there too. On my system it’s file:
/usr/src/linux-headers-2.6.38-10/include/linux/limits.h
#define NAME_MAX 255 /* # chars in a file name */ #define PATH_MAX 4096 /* # chars in a path name including nul */
Sorry, but I’am new here an can’t even comment, save vote. The previous answer (by sfp) should be upped, as it answers the question completely, while the others are partially off. Again, sorry for going besides the rules, but I can’t be quiet when the best answer is at the bottom.
@DavidBalažic: Although true, PATH_MAX under linux is just a guideline, most of the underlying file systems do not have a limitation. This makes it hard to reference paths that greater than that size. I usually use «chunks» of PATH_MAX as a size.
I refer to other answers, please upvote them.
Are there any filename or path length limits on Linux?
Yes, filename and pathname lengths are limited by :
To dynamically get these properties:
- Use functions pathconf and fpathconf as proposed by Michael Aaron Safyan
- Create a filename (or pathname) longer and longer as explained by dogbane
- Use the command getconf as proposed by tim that is also available on Linux:
$ getconf NAME_MAX /mnt/sda2/ 255 $ getconf PATH_MAX /mnt/sda3/ 4096
And for the sake of saving time (and anchoring it to memory):
ext2, ext3, ext4, zfs: no pathname limits; 255 bytes filename limit.
Most programs are limited with absolute paths to PATH_MAX = 4096 , though. That can be worked around if your program is able to use relative paths and you change your working directory first.
It’s because various POSIX APIs such as getcwd and realpath (which you can reimplement in userspace code by reading the metadata for . and then changing to .. and repeating until you hit the filesystem root) rely on PATH_MAX . (Source)
Yes, however, awfully lot of misc library code is prone to break if your code changes current directory at will. A well made code doesn’t break but most of the existing code is not well made.
Those are file system name lengths. «linux» itself has some too. For instance, from bits/stdio_lim.h:
So since the extX filesystems have a lower filename limit than what’s defined in the kernel, you wouldn’t ever hit that limit, unless it also encompases pathnames, right?
that’s what it looks like to me. There’s also PATH_MAX for the path, which is 4096, so it would be hit before the «unlimited» path size on the exts. I’m not sure how the OS resolves its own internal restrictions and those of the FS, never had my arms in that deep. interesting question though.
4096 characters is a helluva path name. I’m sure it could be raised with a recompile, but honestly, /why would you need pathnames that long?/
I’m not sure you would need it or not. I view it more as a protection against malicious or negligent programs (I could easily see a script that behaves poorly and begins creating the same dir recursively. Actually, I’ve made that script, but it was redirecting a web site, not creating dirs. ).
There is no way to determine the maximum length of paths on Linux in a portable way. On my system:
$ getconf PATH_MAX / 4096 $ getconf _POSIX_PATH_MAX / 4096
But I can easily create paths much longer than 4096 characters. Instead see PATH_MAX as a lower bound. You are guaranteed to be able to create paths this long, but you might also be able to create much longer ones.
A simple portable way to find the maximum length empirically is to write a program which creates longer and longer directory chains, and see where it fails. You won’t know exactly why it fails (though you would hope for a suggestive human-readable error message) but you’ll know how far you can safely go. Remember to check for both individual directory length, relative pathname length, and absolute pathname length.
Also, e.g. the Python os.pathconf() module will have some answers; if the Python port is any good, they should be reasonable.
You can’t because some filesystems don’t impose any limits. It would sooner fail with an out of memory error which any program would have a hard time recovering from.
This is the correct answer, except this is due to @BjörnLindqvist comment. PATH_MAX is just a guideline, and 99% of files will probably be within that limit.
Какой максимальной длины может быть имя файла в Linux?
Есть ли ограничение на длину имен файлов и директорий в Linux? Можно ли создать файл с именем, в котором будет 1000 символов?
Да, такое ограничение существует.
Если попробовать создать файл с очень длинным именем, то возникнет ошибка:
touch IktomiisaspiderfairyHewearsbrowndeerskinlegginswithlongsoftfringesoneithersideandtinybeadedmoccasinsonhisfeetHislongblackhairispartedinthemiddleandwrappedwithredredbandsEachroundbraidhangsoverasmallbrownearandfallsforwardoverhisshouldersHeevenpaintshisfunnyfacewithredandyellowanddrawsbigblackringsaroundhiseyesHewearsadeerskinjacketwithbrightcoloredbeadssewedtightlyonitIktomidresseslikearealDakotabraveIntruthhispaintanddeerskinsarethebestpartofhimifeverdressispartofmanorfairy touch: невозможно выполнить touch для 'IktomiisaspiderfairyHewearsbrowndeerskinlegginswithlongsoftfringesoneithersideandtinybeadedmoccasinsonhisfeetHislongblackhairispartedinthemiddleandwrappedwithredredbandsEachroundbraidhangsoverasmallbrownearandfallsforwardoverhisshouldersHeevenpaintshisfunnyfacewithredandyellowanddrawsbigblackringsaroundhiseyesHewearsadeerskinjacketwithbrightcoloredbeadssewedtightlyonitIktomidresseslikearealDakotabraveIntruthhispaintanddeerskinsarethebestpartofhimifeverdressispartofmanorfairy': Слишком длинное имя файла
В Linux максимальная длина имени файла или директории составляет 255 байт.
Но нужно знать, что каждый символ английского алфавита занимает 1 байт. То есть длина в 255 байт эквивалентна 255 символам английского алфавита.
А каждая кириллическая буква занимает 2 байта. Получается, что если создавать файл только из букв русского алфавита, то максимальная длина составит всего 256/2=127,5 или просто 127 символов.
Например, можно создать вот такой файл:
touch ЖилибылипузырьсоломинкаилапотьПошлионивлесдроварубитьДошлидорекиинезнаюткакчерезрекуперейтиЛапотьговоритпузырюПузырьдавайнатебе
Как найти и ограничить длину имени файла в Linux
Одним из интересных аспектов использования любого дистрибутива операционной системы Linux является его способность превращать нас в компьютерных волшебников. В Linux его открытый исходный код позволяет нарушать и/или создавать любые логические правила вычислений. Длина и ограничение имен файлов попадают под такие вычислительные правила.
Поскольку Linux является частью систем на базе Unix, длина имени файла, связанная с этой операционной системой, имеет предел. Ограничение длины имен файлов в операционной системе Linux зависит от конкретной файловой системы.
В этой статье мы определим длину имен файлов в различных файловых системах Linux. После этого мы рассмотрим возможные ограничения, связанные с длиной имени файла.
Ограничение длины имени файла в файловых системах
Ниже приведены ограничения на длину имен файлов в основных файловых системах Unix.
Файловая система | Максимальная длина имени файла |
xt2 | 255 байт |
ext3 | 255 байт |
ext4 | 255 байт |
exFAT | 255 символов UTF-16 |
FAT32 | 255 кодовых единиц UCS-2 с VFAT LFNs |
NTFS | 255 символов |
BTRFS | 255 байтов |
ext3cow | 255 байт |
Однако, поскольку одному символу в представлении Unicode может быть присвоено несколько байт, максимальное количество символов, представляющих имя файла и/или путь к нему, может отличаться. Предел имени файла не изменяется независимо от того, связано ли имя файла с расширением или нет.
Файловая система Linux оказывает сильное влияние на ограничения имен файлов. Например, расширения файловой системы могут изменять максимальную длину имени файла, как в случае с eCryptFS.
Поиск ограничения длины имени файла в Linux
Чтобы найти предел длины имен файлов, которые могут быть созданы и сохранены на вашем компьютере под управлением Linux, мы воспользуемся утилитой командной строки getconf, которая эффективна для запроса переменных конфигурации системы. Мы можем использовать ее вместе с командой grep, чтобы получить установленный предел длины имени файла в нашей системе Linux.
getconf -a | grep -i name_max
Вывод NAME_MAX означает ограничение длины имени файла (255) или максимальную длину имени файла, которую может назначить система Linux.
Если вас интересует ограничение длины пути, команда getconf должна выполняться следующим образом:
getconf -a | grep -i path_max
Подтверждение ограничения длины имени файла
С помощью команды getconf мы убедились, что ограничение на длину имени файла в нашем дистрибутиве Linux OS составляет 255 символов. Давайте попробуем создать файл с помощью команды touch с длиной имени файла 256 символов (на 1 символ больше, чем ограничение в 255 символов).
dict='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' touch $(
Согласно приведенному выше снимку экрана, полученному в результате выполнения команды touch, мы не можем создать имя файла длиной 256 символов, поскольку оно превышает ограничение длины имени файла в 255 символов.
Если мы уменьшим длину имени файла до указанного предела (255 символов), мы сможем создать наш файл.
Значение параметра NAME_MAX, используемое командой getconf, определяет назначенный файловой системой предел длины имени файла. Попытка переопределить это ограничение (NAME_MAX) приведет к переписыванию всего исходного кода файловой системы Linux, включая структуру диска, перед его использованием.
Короче говоря, вам нужно быть хакером ядра, владеющим языком программирования C, чтобы эта реализация стала возможной.
Системный файл /usr/include/linux/limits.h еще больше подчеркивает обсуждаемое ограничение длины имени файла.
cat /usr/include/linux/limits.h
Заключение
Мы поняли, как работает ограничение длины имени файла в Linux, и какие последствия влечет за собой его изменение.