How do I achieve the following goal:
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
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.
$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.
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.
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."
A couple of syntactic issues.
MAXSIZE=500000
, without spaces.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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With