- HowTo: Linux / Unix See File Size Command
- Examples
- Summing up
- How to check the file size in Linux/Unix bash shell scripting
- How to check file size in unix using wc command
- Get the size of a file in a bash script using stat command
- Размер файла в Linux
- Размер файла в Linux
- 1. Nautilus
- 2. Команда ls
- 3. Утилита stat
- 4. Утилита du
- 5. Утилита ncdu
- 6. Утилита find
- Выводы
- How to Display File Size in Human Readable Format (KB, MB, GB) in Linux Terminal
- How can I get the size of a file in a bash script?
- 13 Answers 13
HowTo: Linux / Unix See File Size Command
a] ls command – list directory contents.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | ls/du/stat |
Est. reading time | Less than a one minute |
b] du command – estimate file space usage.
c] stat command – display file or file system status.
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Examples
To determine the size of a file called /bin/grep, enter:
In the above output example, the 175488 is the size of the file. For a more user friendly output, pass the -h option to the ls command:
Here is what we see:
In the above output example, the 172K is the size of the file. The du command provides the same output in a more user friendly way and it hides all other details too:
du -h /bin/grep
Now du command reporting file size on screen:
Finally, stat command also provide file size:
stat /bin/grep
Linux stat command outputs:
The following commands are executed on Apple OS X Unix operating systems to file out the file size of the /usr/bin/vim binary file:
$ ls -l /usr/bin/vim
$ ls -lh /usr/bin/vim
$ stat -x /usr/bin/vim
Fig.01: Finding out file size using various command line options on OS X Unix OS
Summing up
You learned different Linux and Unix commands to display file size using the command-line option. You need to type these commands using the terminal application. One can execute them over remote ssh session too, using the ssh command:
Finding file size using ssh command over the remote session (cloud server)
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How to check the file size in Linux/Unix bash shell scripting
How to check file size in unix using wc command
The wc command shows the number of lines, words, and bytes contained in file. The syntax is as follows to get the file size:
wc -c /path/to/file
wc -c /etc/passwd
Sample outputs:
You can easily extract the first field either using the cut or awk command:
wc -c /etc/passwd | awk ‘
Sample outputs:
OR assign this size to a bash variable:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Get the size of a file in a bash script using stat command
The stat command shows information about the file. The syntax is as follows to get the file size on GNU/Linux stat:
stat -c %s «/etc/passwd»
OR
stat —format=%s «/etc/passwd»
To assign this size to a bash variable:
The syntax is as follows to get the file size on BSD/MacOS stat:
stat -f %z «/etc/passwd»
Please note that if the file is symlink you will get size of that link only with the stat command.
Источник
Размер файла в Linux
В этой небольшой статье мы поговорим о том, как узнать размер файла в Linux с помощью различных утилит. Проще всего узнать этот параметр в графическом интерфейсе, но многим часто приходится работать в терминале и надо знать как эта задача решается там.
Вы узнаете как посмотреть размер файла через файловый менеджер, утилиту ls, а также du. Об этих утилитах у нас есть отдельные статьи, но эта будет нацелена именно на просмотр размера конкретного файла.
Размер файла в Linux
1. Nautilus
Чтобы посмотреть размер файла в файловом менеджере сначала найдите нужный файл и кликните по нему правой кнопкой мыши. В открывшемся меню выберите Свойства:
Программа откроет окно, в котором будут указаны свойства файла, среди них будет и размер:
2. Команда ls
Для того чтобы утилита ls отображала размер файлов в удобном для чтения формате необходимо использовать параметр -h. Например:
Здесь размер отображается в пятой колонке. Чтобы увидеть размер определённого файла надо передать его имя утилите:
ls -lh ‘Снимок экрана от 2020-08-10 20-22-50.png’
Можно ещё вручную указать единицы измерения для показа размера. Для этого используйте опцию —block-size. Например, мегабайты:
ls -l —block-size=M
Вместо ls можно использовать команду ll, её вывод полностью аналогичен команде ls -l:
3. Утилита stat
Программа stat кроме метаданных позволяет выводить размер файла в байтах. Например:
stat ‘Снимок экрана от 2020-08-10 20-22-50.png’
Если нужно показать только размер, используйте опцию -с с указанием формата %s:
stat -c %s ‘Снимок экрана от 2020-08-10 20-22-50.png’
4. Утилита du
Программа du специально предназначена для просмотра размера файлов в папке. Вы можете просмотреть размер конкретного файла, например:
du -h ‘Снимок экрана от 2020-08-10 20-22-50.png’
Опция -h включает вывод размера в удобном для чтения формате. Если вы хотите посмотреть размеры для всех файлов в папке, просто передайте путь к папке:
А чтобы узнать размер папки в Linux используйте опцию -s. Она суммирует размеры всех объектов:
5. Утилита ncdu
Программа ncdu позволяет анализировать дисковое пространство занимаемое файлами и каталогами. Но она не поставляется вместе с системой. Для её установки выполните:
sudo apt install ncdu
Затем просто укажите в параметрах каталог, размер которого вы хотите посмотреть:
Все файлы будут отсортированы по размеру, а в самом низу будет отображен общий размер этой папки:
6. Утилита find
С помощью этой утилиты вы не можете узнать размер файла, зато можете найти файлы с определённым размером. С помощью параметра size можно указать границы размера файлов, которые надо найти. Например, больше чем 2000 килобайт, но меньше чем 2500 килобайт:
/Изображения/ -size +2000k -size -2500k
Размер можно ещё указывать в мегабайтах для этого используйте приставку M, или в байтах, тогда никакой приставки не нужно.
Выводы
В этой небольшой статье мы разобрались как узнать размер файлов linux, а также как посмотреть размер каталога и всех файлов в нём с помощью различных утилит. А какие способы просмотра размера используете вы? Напишите в комментариях!
Источник
How to Display File Size in Human Readable Format (KB, MB, GB) in Linux Terminal
You probably already know that you can use ls command with long listing option -l to show file size in Linux.
But unfortunately, the long listing shows the file size in blocks and that’s not of much use to us humans.
Good thing is that you can combine the option -l with -h to show the file size in human readable format.
As you can see, it is better to display file size in human-readable format.
As you can see, file sizes are now displayed in K (for KB), M for (MB). If the file size is in Bytes, it is not displayed with any suffix. In the above example, char.sh is 140 Bytes in size.
Did you notice the size of new_dir directory? It is 4 KB. If you use ls -lh command on directories, it always shows the size of directory as 4.0 K.
By default, the block size in most Linux system is 4096 Bytes or 4 KB. A directory in Linux is simply a file with the information about the memory location of all the files in it.
You can force ls command to display file size in MB with the —block-size flag.
The problem with this approach is that all the files with size less than 1 MB will also be displayed with file size 1 MB.
The ls command also has -s option to display size. You should combine with -h to show the file size in human readable form.
Here’s the output:
You can also use the stat command in Linux to check the file size.
I hope you find this quick tip helpful in seeing the file size in Linux.
Источник
How can I get the size of a file in a bash script?
How can I get the size of a file in a bash script?
How do I assign this to a bash variable so I can use it later?
13 Answers 13
Your best bet if on a GNU system:
In a bash script :
NOTE: see @chbrown’s answer for how to use stat in terminal on Mac OS X.
The problem with using stat is that it is a GNU (Linux) extension. du -k and cut -f1 are specified by POSIX and are therefore portable to any Unix system.
Solaris, for example, ships with bash but not with stat . So this is not entirely hypothetical.
ls has a similar problem in that the exact format of the output is not specified, so parsing its output cannot be done portably. du -h is also a GNU extension.
Stick to portable constructs where possible, and you will make somebody’s life easier in the future. Maybe your own.
You could also use the «word count» command ( wc ):
The problem with wc is that it’ll add the filename and indent the output. For example:
If you would like to avoid chaining a full interpreted language or stream editor just to get a file size count, just redirect the input from the file so that wc never sees the filename:
This last form can be used with command substitution to easily grab the value you were seeking as a shell variable, as mentioned by Gilles below.
BSD’s (macOS’s) stat has a different format argument flag, and different field specifiers. From man stat(1) :
- -f format : Display information using the specified format. See the FORMATS section for a description of valid formats.
- . the FORMATS section .
- z : The size of file in bytes.
So all together now:
NOTE: see @b01’s answer for how to use the stat command on GNU/Linux systems. 🙂
Depends what you mean by size.
will give you the number of bytes that can be read from the file. IOW, it’s the size of the content of the file. It will however read the contents of the file (except if the file is a regular file or symlink to regular file in most wc implementations as an optimisation). That may have side effects. For instance, for a named pipe, what has been read can no longer be read again and for things like /dev/zero or /dev/random which are of infinite size, it’s going to take a while. That also means you need read permission to the file, and the last access timestamp of the file may be updated.
That’s standard and portable, however note that some wc implementations may include leading blanks in that output. One way to get rid of them is to use:
or to avoid an error about an empty arithmetic expression in dash or yash when wc produces no output (like when the file can’t be opened):
ksh93 has wc builtin (provided you enable it, you can also invoke it as command /opt/ast/bin/wc ) which makes it the most efficient for regular files in that shell.
Various systems have a command called stat that’s an interface to the stat() or lstat() system calls.
Those report information found in the inode. One of that information is the st_size attribute. For regular files, that’s the size of the content (how much data could be read from it in the absence of error (that’s what most wc -c implementations use in their optimisation)). For symlinks, that’s the size in bytes of the target path. For named pipes, depending on the system, it’s either 0 or the number of bytes currently in the pipe buffer. Same for block devices where depending on the system, you get 0 or the size in bytes of the underlying storage.
You don’t need read permission to the file to get that information, only search permission to the directory it is linked to.
By chronological order, there is:
returns the st_size attribute of $file ( lstat() ) or:
same except when $file is a symlink in which case it’s the st_size of the file after symlink resolution.
zsh stat builtin (now also known as zstat ) in the zsh/stat module (loaded with zmodload zsh/stat ) (1997):
or to store in a variable:
obviously, that’s the most efficient in that shell.
GNU stat (2001); also in BusyBox stat since 2005 (copied from GNU stat ):
(note the meaning of -L is reversed compared to IRIX or zsh stat .
Or you can use the stat() / lstat() function of some scripting language like perl :
AIX also has an istat command which will dump all the stat() (not lstat() , so won’t work on symlinks) information and which you could post-process with, for example:
(size after symlink resolution)
Long before GNU introduced its stat command, the same could be achieved with GNU find command with its -printf predicate (already in 1991):
One issue though is that doesn’t work if $file starts with — or is a find predicate (like ! , ( . ).
The standard command to get the stat() / lstat() information is ls .
POSIXly, you can do:
and add -L for the same after symlink resolution. That doesn’t work for device files though where the 5 th field is the device major number instead of the size.
For block devices, systems where stat() returns 0 for st_size , usually have other APIs to report the size of the block device. For instance, Linux has the BLKGETSIZE64 ioctl() , and most Linux distributions now ship with a blockdev command that can make use of it:
However, you need read permission to the device file for that. It’s usually possible to derive the size by other means. For instance (still on Linux):
Should work except for empty devices.
An approach that works for all seekable files (so includes regular files, most block devices and some character devices) is to open the file and seek to the end:
With zsh (after loading the zsh/system module):
For named pipes, we’ve seen that some systems (AIX, Solaris, HP/UX at least) make the amount of data in the pipe buffer available in stat() ‘s st_size . Some (like Linux or FreeBSD) don’t.
On Linux at least, you can use the FIONREAD ioctl() after having open the pipe (in read+write mode to avoid it hanging):
However note that while it doesn’t read the content of the pipe, the mere opening of the named pipe here can still have side effects. We’re using fuser to check first that some process already has the pipe open to alleviate that but that’s not foolproof as fuser may not be able to check all processes.
Now, so far we’ve only been considering the size of the primary data associated with the files. That doesn’t take into account the size of the metadata and all the supporting infrastructure needed to store that file.
Another inode attribute returned by stat() is st_blocks . That’s the number of 512 byte blocks that is used to store the file’s data (and sometimes some of its metadata like the extended attributes on ext4 filesystems on Linux). That doesn’t include the inode itself, or the entries in the directories the file is linked to.
Size and disk usage are not necessarily tightly related as compression, sparseness (sometimes some metadata), extra infrastructure like indirect blocks in some filesystems have an influence on the latter.
That’s typically what du uses to report disk usage. Most of the commands listed above will be able to get you that information.
- POSIXLY_CORRECT=1 ls -sd — «$file» | awk ‘
‘ - POSIXLY_CORRECT=1 du -s — «$file» (not for directories where that would include the disk usage of the files within).
- GNU find — «$file» -printf ‘%b\n’
- zstat -L +block — $file
- GNU stat -c %b — «$file»
- BSD stat -f %b — «$file»
- perl -le ‘print((lstat shift)[12])’ — «$file»
Источник