Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using bash to print to screen using conditional

Tags:

bash

Input:

number=5
if $number > 0; echo "Yes"; else echo "No";fi

My output is:

bash: 5: command not found...
No

I only want Yes or No, so what's wrong with the syntax?

like image 863
SaltedPork Avatar asked Dec 11 '25 08:12

SaltedPork


2 Answers

if requires a command (actually, a command list), not an expression. The test command is what you want. (You are also missing the then keyword, which terminates the condition.)

if test "$number" -gt 0; then
    echo "Yes"
else
    echo "No"
fi
like image 153
chepner Avatar answered Dec 14 '25 04:12

chepner


For bash arithmetic, prefer modern style :

if ((number > 0)); then
    echo "Yes"
else
    echo "No"
fi

or using boolean logic :

((number > 0)) && echo "Yes" || echo "No"
like image 21
Gilles Quenot Avatar answered Dec 14 '25 03:12

Gilles Quenot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!