-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

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

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest