0

I'm trying to do a script that is used with two arguments - a file and an integer. It should check if the arguments are valid, otherwise exit with 1. Then it should either return 0 if the file is smaller than second argument, or echo size of the file to stdout. The script keeps returning value 123 instead of 1 or 0. Where is the problem? Thanks.

#!/bin/bash
if [ $# -eq 2 ];
then
    if test $2 -eq $2  > /dev/null 2>&1
    then
        if [ -f $1 ];
        then
            if [ $(stat -c %s $1) -ge $2 ];
            then
                echo $(stat -c %s $1)
            else
                exit 0
            fi
        else
            exit 1
       fi
    else
        exit 1
    fi
else
    echo 042f9
    exit 1
fi
S M
  • 25
  • 4
  • 1
    Please indent your code. Or better, exit early (i.e. if arg count wrong then exit) so you don't have to nest if/elses. – Mat May 12 '22 at 09:35
  • Run the program with tracing turned on (e.g. `bash -x PROG FILE SIZE`) to find exactly where the `123` is coming from. See [How can I debug a Bash script?](https://stackoverflow.com/q/951336/4154375) and [How to debug a bash script?](https://unix.stackexchange.com/q/155551/264812). – pjh May 12 '22 at 10:38

1 Answers1

1

I do not know where the "123" output comes from, but I would do it like this:

#!/bin/bash

# Must have 2 arguments
if [[ $# -ne 2 ]]
then
    printf "042f9\n"
    exit 1
fi

# File must exist
if [[ ! -f "$1" ]]
then
    exit 1
fi

# File size > $2 check
filesize=$(stat -c %s "$1")
if [[ $filesize -ge $2 ]]
then
    printf "%d" "$filesize"
else
    exit 1
fi

A couple notes for your scripts (IMHO):

  • Like Mat mentioned in the comments, test 1 condition and exit right away. When I read your script, I had to go to the end to see what happens if the number of arguments is wrong. Logically there is nothing wrong with your code, it is just making it easier to read.
  • For bash, use [[ ]] to test if conditions.
  • I try never to call a function or command twice. That is why I stored the result of the stat command in a variable. If you use it more than once, store it, do not call the command again.
  • No need for ; since you put your then on the next line anyway.
  • Always double-quote your variables, especially if they are filenames. Weird filenames break so many scripts!
  • Finally use printf instead of echo. For simple cases, its the same, but echo does have some issues (https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo).

Possible return values:

  • the size of the file, and the exit value is 0 ($?). The file is larger than argument 2 value.
  • "042f9", and the exit value is 1 ($?). Arguments error.
  • nothing, and the exit value is 1 ($?). Missing file error, or the file is smaller than argument 2 value.
Nic3500
  • 8,144
  • 10
  • 29
  • 40