7

How can I get the size of a file into a variable?

ls -l | grep testing.txt | cut -f6 -d' '

gave the size, but how can I store it in a shell variable?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
webminal.org
  • 44,948
  • 37
  • 94
  • 125

6 Answers6

20
filesize=$(stat -c '%s' testing.txt)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
4

You can do it this way with ls (check the man page for the meaning of -s)

var=$(ls -s1 testing.txt | awk '{print $1}')

Or you can use stat with -c '%s'.

Or you can use find (GNU):

var=$(find testing.txt -printf "%s")
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • the find solution works on MINGW and git bash on Windows. None of the other answers work on MINGW. – JDiMatteo Oct 17 '14 at 15:17
  • If you wanted a version that worked on *every* POSIX system, `wc -c` would be better than either relying on `ls` behavior *or* on having GNU `find` or `stat` available. – Charles Duffy Mar 23 '15 at 20:19
  • Note that wc -c is more accurate for pseudo files like /proc/cpuinfo – pixelbeat Mar 24 '15 at 03:32
2
size() {
  file="$1"
  if [ -b "$file" ]; then
    /sbin/blockdev --getsize64 "$file"
  else
    wc -c < "$file"  # Handles pseudo files like /proc/cpuinfo
    # stat --format %s "$file"
    # find "$file" -printf '%s\n'
    # du -b "$file" | cut -f1
  fi
}

fs=$(size testing.txt)
pixelbeat
  • 30,615
  • 9
  • 51
  • 60
1
size=`ls -l | grep testing.txt | cut -f6 -d' '`
Burntime
  • 2,334
  • 2
  • 15
  • 20
  • There's no guarantee that the size will be in field 6 when space-delimited. – Charles Duffy Mar 23 '15 at 20:06
  • This is also inefficient because piping `ls` into `grep` lists *all* files in the directory and sorts their names (which can take a substantial amount of time in a directory with thousands of files), and additionally error-prone because `grep testing.txt` also returns files with names like `not_testingatxt_file` (as `.` in a regex means match-any-character). – Charles Duffy Mar 23 '15 at 20:09
0

You can get the file size in bytes with the command wc, which is fairly common on Linux systems since it's part of GNU coreutils:

wc -c < file

In a Bash script you can read it into a variable like this:

FILESIZE=$(wc -c < file)

From man wc:

-c, --bytes
       print the byte counts
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
-2
    a=\`stat -c '%s' testing.txt\`;
    echo $a
user2720864
  • 8,015
  • 5
  • 48
  • 60
ransell
  • 1
  • 1