Accueil > Système > How to check the file size in Linux/Unix bash shell scripting

How to check the file size in Linux/Unix bash shell scripting

22/12/2023 Categories: Système Tags: , , , ,
Print Friendly, PDF & Email

 

How to check file size in unix using wc command

The wc command shows the number of lines, words, and bytes contained in file. The syntax is as follows to get the file size:
wc -c /path/to/file
wc -c /etc/passwd

Sample outputs:

5253 /etc/passwd

You can easily extract the first field either using the cut or awk command:
wc -c /etc/passwd | awk '{print $1}'
Sample outputs:

5253

OR assign this size to a bash variable:

myfilesize=$(wc -c "/etc/passwd" | awk '{print $1}')
printf "%d\n" $myfilesize
echo "$myfilesize"

How to get the size of a file in a bash script using stat command

The stat command shows information about the file. The syntax is as follows to get the file size on GNU/Linux stat:
stat -c %s "/etc/passwd"
OR
stat --format=%s "/etc/passwd"
To assign this size to a bash variable:

myfilesize=$(stat --format=%s "/etc/passwd")
echo "$myfilesize"
## or ##
myFileSizeCheck=$(stat -c %s "/etc/resolv.conf")
printf "My file size = %d\n" $myFileSizeCheck

The syntax is as follows to get the file size on BSD/MacOS stat:
stat -f %z "/etc/passwd"
Please note that if the file is symlink you will get size of that link only with the stat command.

du command example

The syntax is

du --apparent-size --block-size=1  "/etc/passwd"
fileName="/etc/hosts"
mfs=$(du --apparent-size --block-size=1  "$fileName" | awk '{ print $1}')
echo "$fileName size = ${mfs}"

Sample outputs from above commands:

Fig.01: How to check size of a file using a bash/ksh/zsh/sh/tcsh shell?Fig.01: How to check size of a file using a bash/ksh/zsh/sh/tcsh shell?

 

Find command example

The syntax is:

find "/etc/passwd" -printf "%s"
find "/etc/passwd" -printf "%s\n"
fileName="/etc/hosts"
mysize=$(find "$fileName" -printf "%s")
printf "File %s size = %d\n" $fileName $mysize
echo "${fileName} size is ${mysize} bytes."
Lire aussi:  What are useful CLI tools for Linux system admins ?
Categories: Système Tags: , , , ,
Les commentaires sont fermés.