Linux file size

I want to get the file size in a variable? How to do it?

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

gave a size, but how to save it in a shell variable?

+7
linux shell
source share
6 answers
 filesize=$(stat -c '%s' testing.txt) 
+18
source share

you can do this with ls (check the man page for the -s value)

 $ 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") 
+4
source share
 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) 
+3
source share
 size=`ls -l | grep testing.txt | cut -f6 -d' '` 
+1
source share

You can get the file size in bytes with the wc command, which is pretty common on Linux systems, as it is part of GNU coreutils

 wc -c < file 

In a shell script, you can read it into a variable as follows:

 FILESIZE=$(wc -c < file) 

From man wc :

 -c, --bytes print the byte counts 
0
source share
  a=\`stat -c '%s' testing.txt\`; echo $a 
-one
source share

All Articles