Timeline for How can I get the size of a file in a bash script?
Current License: CC BY-SA 3.0
9 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Mar 9, 2021 at 21:12 | comment | added | Brian |
@AmedeeVanGasse - --bytes is unfortunately not available on BSD Unix (e.g. macos). Important since this answer is talking about POSIX compatibility.
|
|
| Aug 6, 2019 at 9:42 | comment | added | Hugo H |
Using du with --apparent-size flag will return a more precise size (as stated on man : print apparent sizes, rather than disk usage; although the apparent size is usually smaller, it may be larger due to holes in ('sparse') files, internal fragmentation, indirect blocks, and the like)
|
|
| Apr 1, 2019 at 16:19 | comment | added | Nemo |
@fralau: The OP wants to "assign this to a bash variable so they can use it later", so it is much more likely they want an actual numeric value, not a human-readable approximation. Also, -h is a GNU extension; it is not standard
|
|
| Apr 1, 2019 at 8:58 | comment | added | fralau |
The -h ("human") option of du will produce the most appropriate answer for general cases: file_size=`du -h "$filename" | cut -f1 , as it will display K (kilobytes), M (Megabytes) or G (Gigabytes) as appropriate.
|
|
| Jan 8, 2019 at 12:56 | comment | added | Amedee Van Gasse |
This, with --bytes or -b instead of -k, should be the accepted answer.
|
|
| Jan 9, 2016 at 22:03 | comment | added | vonbrand | @Gilles, sparse files (i.e., ones with holes in them) report less than the length. | |
| Jul 14, 2011 at 10:00 | comment | added | Gilles 'SO- stop being evil' |
du doesn't give the size of the file, it gives an indication of how much space the file uses, which is subtly different (usually the size reported by du is the size of the file rounded up to the nearest number of blocks, where a block is typically 512B or 1kB or 4kB).
|
|
| Jul 14, 2011 at 0:59 | history | migrated | from stackoverflow.com (revisions) | ||
| Jul 13, 2011 at 16:34 | history | answered | Nemo | CC BY-SA 3.0 |