- 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
- HowTo: Linux / Unix See File Size Command
- Examples
- Summing up
- Размер файла в 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 to get the physical size of a file in Linux?
- 2 Answers 2
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.
Источник
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
Источник
Размер файла в 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 to get the physical size of a file in Linux?
I can use ls -l to get the logical size of a file, but is there a way to get the physical size of a file?
2 Answers 2
ls -l will give you the apparent size of the file, which is the number of bytes a program would read if it read the file from start to finish. du would give you the size of the file «on disk».
By default, du gives you the size of the file in number of disk blocks, but you may use -h to get a human readable unit instead. See also the manual for du on your system.
Note that with GNU coreutil’s du (which is probably what you have on Linux), using -b to get bytes implies the —apparent-size option. This is not what you want to use to get number of bytes actually used on disk. Instead, use —block-size=1 or -B 1 .
With GNU ls , you may also do ls -s —block-size=1 on the file. This will give the same number as du -B 1 for the file.
This means that this is a 512 MB file that takes about 24 KB on disk. It is a sparse file (mostly zeros that are not actually written to disk but represented as logical «holes» in the file). Sparse files are common when working with pre-allocated large files, e.g. disk images for virtual machines or swap files etc. Creating a sparse file is quick, while filling it with zeros is slow (and unnecessary).
See also the manual for fallocate on your Linux system.
Источник