Search code examples
linuxcentoscentos7redhat

Bash shell don't recognize else statement


I am trying to build a script that asks the user to enter the file size and path, if the file size is bigger then the limit the file should bd delete, the problem is even if the file is smaller then the entered value, the script delete that file anyway, I think there is an error in my Else statement

and I already tried "https://www.shellcheck.net/" and give me this error and I didn't know how to solve it if [ "$SIZE" -gt "$limit" ]; ^-- SC2154: limit is referenced but not assigned.

#!/bin/bash
 limit="$1"
shift 1 
for file in "$@"; do
SIZE="$(stat --format="%s" "$file")"
if [ "$SIZE" -gt "$limit" ];
then
echo "$file is $SIZE bytes. Deleting..; -rm $file"
 else 
echo "file is smaller then limit no delete"
 fi
 done

Edit: I removed 'read' and now I get this error '[: -gt: unary operator expected ' and even if the file size is bigger then the entered value its go directly to else statement


Solution

  • ShellCheck is on the right track: limit is indeed not being assigned, because your read statement is invalid. Your script therefore always thinks limit=0 and therefore that all files should be deleted.

    Instead of

    read -i limit="$1"
    

    you should just do

    limit="$1"
    

    Here is the complete script with this change:

    #!/bin/bash
    limit=$1
    shift 1
    for file in "$@"; do
    SIZE="$(stat --format="%s" "$file")"
    if [ "$SIZE" -gt "$limit" ];
    then
    echo "$file is $SIZE bytes. Deleting..; -rm $file"
     else
    echo "file is smaller then limit no delete"
     fi
     done
    

    And here's an example of running it:

    $ ls -l big small
    -rw-r--r-- 1 me me 505 May 19 15:01 big
    -rw-r--r-- 1 me me 495 May 19 15:01 small
    
    $ ./myscript 500 big small
    big is 505 bytes. Deleting..; -rm big
    file is smaller then limit no delete