-gt: unary operator expected shell script

Getting this error after the upgrade packages in ubuntu.

#!/bin/bash
used=$(df -H | grep 'rootfs' | cut -d "G" -f 4 | cut -d "%" -f 1)
limit=90
if [ $used -gt $limit ]; then Or [ "$used" -gt "$limit" ] Or [ "$used" -ge 90 ]
#delete file and mail command;
fi

Error

[: -gt: unary operator expected

1 Answer

The variable used is empty, leading to the error message regarding unary operator. Possible reason could be there is no rootfs in df -H output i.e. in your system.

$ foo=
$ [ $foo -gt 10 ] && echo OK
bash: [: -gt: unary operator expected

You have also some other issues in your script, the OR logic should be put as:

[ "$foo" -gt "$bar" ] || [ "$foo" -ge 90 ]

Also better use the shell keywod [[ instead of test ([) command to avoid many pitfalls:

[[ "$foo" -gt "$bar" ]] || [[ "$foo" -ge 90 ]]

For arithmetic comparisons, you can also use (( and regular arithmetic operators:

(( "$foo" > "$bar" )) || (( "$foo" >= 90 ))

You don't even need to put $ in-front of the variable name:

(( foo > bar )) || (( foo >= 90 ))

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like