- 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
- Выводы
- HowTo: Linux / Unix See File Size Command
- Examples
- Summing up
- How to Display File Size in Human Readable Format (KB, MB, GB) in Linux Terminal
- How to display files sizes in MB in Linux/Ubuntu
- amin nahdy
- This Post Has 5 Comments
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, а также как посмотреть размер каталога и всех файлов в нём с помощью различных утилит. А какие способы просмотра размера используете вы? Напишите в комментариях!
Источник
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 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 display files sizes in MB in Linux/Ubuntu
Sometimes we want to see the sizes of files as returned by the ls command displayed in some reasonable format or in other words in human readable presentation.
To display the file sizes in units like 7K, 5M, 8.2G, etc… use the -lh option with ls.
Note that -h is a GNU coreutils extension.
To display the sizes rounded up to the nearest MiB (2^20 bytes), you should use the command :
ls -l –block-size=M
If the M suffix bothers you in some way, you can get rid of it by using –block-size=1M.
file size linux
If however you want to see the size in MB (10^6 bytes) instead, you should use the command with the option –block-size=MB.
To understand the differences between the units MiB and MB, have a look at the table below (courtesy majordifferences.com) :
For more on this, you may want to visit the man page for ls.
Simply type in man ls and look up the word SIZE. In case you are interested, you will find other units as well (besides MB/MiB).
If you like the content, we would appreciate your support by buying us a coffee. Thank you so much for your visit and support.
amin nahdy
This Post Has 5 Comments
Absolutely and utterly WRONG !
Windows has NEVER EVER EVER, used IEC (Mebibyte etc) notation.
Windows CORRECTLY reports filesizes as KB, MB, GB and TB etc ,always has and is one of the few current OSes that does.
I guess it has to have something going for it, right ?
In fact ALL computer Operating Systems used to, until fairly recently that is with this IEC standard rubbish with mebi, gibi, kibi nonsense creeping in.
A Megabyte IS and ALWAYS WILL BE 1024KB
1 KB = 1024 Bytes
1 MB = 1024 x 1KB or 1024 x 1024 bytes
1 GB = 1024 X 1MB or 1024 x 1024 x 1024 bytes
so on and so forth and no sign of those stupid KiB, MiB, GiB things anywhere.
It’s laughable (and very annoying) really that people who should know better are swallowing this garbage all to come in line with weights and measures ! ha !
BTW I’ve been using computers for over 40 years so there’s a fair chance I know what I am talking about here.
@Net2
Could your point be that some group (IEC) arbitrarily decided to TRY and change things to protect lying Hard disk manufacturers (as well as come in line with weights and measures) ?
That article means nothing to me and doesn’t hold any information I didn’t already know.
Look, I love using Linux but it has become infested with this nonsense but I am FORCED to show files with those ridiculous IEC labels so I can see the real size of my files as the ‘new’ MB, GB etc are NOT the REAL filesize.
Back in the late 70s, 80s and 90s there was consensus as to names of filesizes, now, because of the stupid IEC and people that go along with them, it’s a complete dog’s breakfast !
I see MiB and I say Megabyte and I will ’til the day I die.
I’m going to have to agree with Fred. 1 kB = 1024 B. That’s a lower case k. Never use a upper case k when writing, km, kL, k$, ky, kg, ks and so on. When talking about temperature, if you want to use Kelvin, never put a ° symbol. For example, 298 K.
Back to computers. There is no confusion at all. I am not confused. 1 kB = 1024 B. 1 MB = 1024 * 1024 B.
When I write software, that is the standard that I use.
That is the standard used on Intel and AMD’s websites. Look at their cache sizes. That is the standard used in computer science. I am not interested in how hard disk manufacturers are confused.
Источник