Linux file size in directory что это

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.

Источник

Checking Directory Size with du Command in Linux

Knowing the size of a file is easy in Linux. All you have to do is to use the -l and -h option with the ls command and it will show you the file size along with file permissions and file timestamps. Here’s a sample output:

You would notice something strange. The ls command shows the size of all the directories as 4 KB. That cannot be correct, can it be? Of course not.

The size of a folder or directory in Linux can be found using the du command. du here stands for disk usage. I’ll explain the logic behind the 4.0K size for the directories later in this tutorial. For the moment, let’s focus on getting the directory size.

If you want to check the directory size in Linux, you can use this command:

This will give you the total size of the said directory in human-readable format, i.e. KB, MB or GB.

Using du command to get directory size in Linux

I am going to show you various examples of the du command that you can use to check the directory size and the disk utilization.

The syntax for the du command is pretty simple.

Let’s see how to use the du command to get the file and directory size information in Linux.

Here’s the structure of the “tutorials” directory I am going to use in this tutorial:

Now if I run the du command in the “tutorials” directory, it will show the sizes of all the subdirectories and then sum the sizes of all the subdirectories and the files at the bottom of it.

This is the output for the tutorials directory.

Show disk size in human-readable format

Now the problem with the above output of the du command is that you don’t know if the 100 is 100KB or 100MB or 100GB. Don’t worry, you can change this behavior and display the directory size in a human readable format with the option -h.

Here’s the much easier to read output now:

You can use -m option for MB and -k option for KB instead of -h. But even if the size is less than 1 MB, it will always show the size as 1MB. This is why using -h option is always a better option.

Show the sizes of the files as well

Did you notice that the tutorials directory has several files but they don’t show up in the du command output? It’s because though the file size are counted in the total sum of the directory size, the files are not displayed by default.

To display the size of files along with the directories, you can use the -a option. It would be better if you combine it with -h option to get the sizes in human readable format.

Now the output will show the files along with the directories:

Bonus Tip: Solving the mystery of 4 KB

Note that the sizes may seem like that have been rounded off. I mean all the sizes are in the multiple of 4K. In fact, apart from the empty files, all the files are of at least 4 KB in size. Is that a coincidence? Not really.

Even if the text of the file is in bytes, the minimum file size is 4K because that’s the minimum block size of the filesystem. Irrespective of the size of the text on the file, it will be allotted at least one block of 4KB memory on the disk.

And since the memory blocks are 4KB in size, the sizes you’ll see will always be in the multiple of 4KB.

Now, you probably already know that everything is file in UNIX/Linux. A directory is essentially a file that has the information about all the location of all the files it ‘contains’.

So, when you use the ls command, it treats the directory as a file and shows its size which is one memory block and thus the size displayed is 4KB.

Show only the total size of the directory in Linux

If you find the output of the du command too verbose and would like to see just the total size of the directory in a human readable format, you can use the sum option -s.

Now the output will be just one line showing the total size of the directory:

Show the disk usage by multiple directories

It’s not that you are restricted to check the size of only one directory at a time. You can specify multiple directories in the du command.

For example, I am going to use the -sh options to show the total size of two directories here.

The output will show the size of both the directories individually:

Show the grand total of all the directory sizes

In the above example, you saw the total sizes of both the directories individually. You can use the option -c to show a grand total for the sum of all the directories in the output.

As you can see in the output, it sums up the sizes and gives you the grand total:

Don’t show the sizes of the subdirectories

What if you want to check the sizes of the all the directories in the current folder? By default, du command will go into the subdirectories of all the directories and the output becomes difficult to figure out specially if you have too many nested directories.

What you can do is to define the depth level to check while showing the sizes for the subdirectories.

So, if you want to see the sizes of the directories in the current folder, you can set the depth to 1 like this:

Now the output will show the subdirectories only in the current directory. It won’t go further than this.

If you cannot remember the –max-depth, you can use its short form -d flag:

Exclude certain type of files while calculating disk size

The du command gives you option to exclude certain type of files. You can use regex along with the –exclude option.

For example, to calculate the sum of all the files excluding files with extension txt, this command can be used:

And now if you see the output, the total size of the directory would have been reduced:

Bonus Tip: Finding the biggest subdirectory

You can combine the output of the du command with the sort command to sort the directories by the order of their size.

This will show the directories in the reverse order of their size i.e. the biggest directory on the top.

Of course the top one is the directory itself but the second one gives you the biggest subdirectory.

You can further combine with the head command or the tail command to get the x largest file or smallest files/directories.

Did you find it useful?

I have tried to explain all the essential usage of the du command in Linux. But as always, there are many more options available for the command that you can find in its man page. If you just wanted to find out the size of a directory in Linux, this tutorial should give you enough information. If you want to check disk space in Linux, use the df command.

Did you like the tutorial? Did it help you? Let me know in the comments. If you have some other cool tip about du command, why not share it with us?

Источник

Читайте также:  Windows 10 desktop html
Оцените статью