Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file's size is greater than a certain value in Bash

Tags:

How do I achieve the following goal:

  • I need to check the size of a file
  • Then compare this file size to a fixed number using an if condition and corresponding conditional statement

So far, I have the following:

#!/bin/bash  # File to consider FILENAME=./testfile.txt  # MAXSIZE is 5 MB MAXSIZE = 500000  # Get file size FILESIZE=$(stat -c%s "$FILENAME") # Checkpoint echo "Size of $FILENAME = $FILESIZE bytes."  # The following doesn't work if [ (( $FILESIZE > MAXSIZE)) ]; then     echo "nope" else     echo "fine" fi 

With this code, I can get the file name in the variable $FILESIZE, but I am unable to compare it with a fixed integer value.

#!/bin/bash filename=./testfile.txt maxsize=5 filesize=$(stat -c%s "$filename") echo "Size of $filename = $filesize bytes."  if (( filesize > maxsize )); then     echo "nope" else     echo "fine" fi 
like image 620
bipster Avatar asked Oct 19 '17 06:10

bipster


People also ask

How do I see file size in bash?

Another method we can use to grab the size of a file in a bash script is the wc command. The wc command returns the number of words, size, and the size of a file in bytes.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

How do I compare values in bash?

Comparison operators are operators that compare values and return true or false. When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command.

How do I determine the size of a shell file?

Getting file size using find command 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."


1 Answers

A couple of syntactic issues.

  1. The variable definitions in Bash do not take spaces. It should have been MAXSIZE=500000, without spaces.
  2. The way comparison operation is done is incorrect. Instead of if [ (( $FILESIZE > MAXSIZE)) ];, you could very well use Bash’s own arithmetic operator alone and skip the [ operator to just if (( FILESIZE > MAXSIZE)); then

If you are worried about syntax issues in your script, use ShellCheck to syntax check your scripts and fix the errors as seen from it.


As a general coding practice, use lowercase user-defined variables in Bash to avoid confusing them with the special environment variables which are interpreted for different purposes by the shell (e.g., $HOME and $SHELL).

like image 88
Inian Avatar answered Oct 14 '22 13:10

Inian