- 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
- How to Display File Size in Human Readable Format (KB, MB, GB) in Linux Terminal
- How do I make `ls` show file sizes in megabytes?
- 2 Answers 2
- Размер файла в Linux
- Размер файла в Linux
- 1. Nautilus
- 2. Команда ls
- 3. Утилита stat
- 4. Утилита du
- 5. Утилита ncdu
- 6. Утилита find
- Выводы
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.
Источник
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 do I make `ls` show file sizes in megabytes?
What commands do I need for Linux’s ls to show the file size in MB?
2 Answers 2
ls -l —block-size=M will give you a long format listing (needed to actually see the file size) and round file sizes up to the nearest MiB.
If you want MB (10^6 bytes) rather than MiB (2^20 bytes) units, use —block-size=MB instead.
If you don’t want the M suffix attached to the file size, you can use something like —block-size=1M . Thanks Stéphane Chazelas for suggesting this.
If you simply want file sizes in «reasonable» units, rather than specifically megabytes, then you can use -lh to get a long format listing and human readable file size presentation. This will use units of file size to keep file sizes presented with about 1-3 digits (so you’ll see file sizes like 6.1K , 151K , 7.1M , 15M , 1.5G and so on.
The —block-size parameter is described in the man page for ls; man ls and search for SIZE . It allows for units other than MB/MiB as well, and from the looks of it (I didn’t try that) arbitrary block sizes as well (so you could see the file size as a number of 429-byte blocks if you want to).
Note that both —block-size and -h are GNU extensions on top of the Open Group’s ls , so this may not work if you don’t have a GNU userland (which most Linux installations do). The ls from GNU Coreutils 8.5 does support —block-size and -h as described above. Thanks to kojiro for pointing this out.
Источник
Размер файла в 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, а также как посмотреть размер каталога и всех файлов в нём с помощью различных утилит. А какие способы просмотра размера используете вы? Напишите в комментариях!
Источник