How can I get the size of a file in a bash script?

Your best bet if on a GNU system:

stat --printf="%s" file.any

From man stat:

%s total size, in bytes

In a bash script :

#!/bin/bash
FILENAME=/home/heiko/dummy/packages.txt
FILESIZE=$(stat -c%s "$FILENAME")
echo "Size of $FILENAME = $FILESIZE bytes."

NOTE: see @chbrown's answer for how to use stat in terminal on Mac OS X.


file_size_kb=`du -k "$filename" | cut -f1`

The problem with using stat is that it is a GNU (Linux) extension. du -k and cut -f1 are specified by POSIX and are therefore portable to any Unix system.

Solaris, for example, ships with bash but not with stat. So this is not entirely hypothetical.

ls has a similar problem in that the exact format of the output is not specified, so parsing its output cannot be done portably. du -h is also a GNU extension.

Stick to portable constructs where possible, and you will make somebody's life easier in the future. Maybe your own.


You could also use the "word count" command (wc):

wc -c "$filename" | awk '{print $1}'

The problem with wc is that it'll add the filename and indent the output. For example:

$ wc -c somefile.txt
    1160 somefile.txt

If you would like to avoid chaining a full interpreted language or stream editor just to get a file size count, just redirect the input from the file so that wc never sees the filename:

wc -c < "$filename"

This last form can be used with command substitution to easily grab the value you were seeking as a shell variable, as mentioned by Gilles below.

size="$(wc -c <"$filename")"

Tags:

Shell

Bash

Files