I have a bash script where I get a number from a string and convert it to an INT using the expr command in bash. I then want to see if that first number is greater than the second number. When I run the script, I am getting: unary operator expected
My script is:
#!/bin/bash
name1="19.5"
name2="19.1"
name3=`expr $name1`
name4=`expr $name2`
if [ $name3 >= $name4 ]; then
echo "${name3} is greater than ${name4}"
fi
What am I doing wrong? Am I not converting the string number to an INT correctly?
> is the operator for redirecting standard output. Hence you are trying to redirect the stdout of the ] command to a file named =, which leaves [ with only two arguments ($name3 and $name4).
Hence, if you want to do textual comparision, then instead of [, you have to use [[ ... ]], which is not a command, but part of bash syntax, and between the brackets, the redirection rules don't apply. However, you still don't have <= as an operator, but only < and >. In your case, this will be
if [[ ! $name4 < $name3 ]]; then ....
If you want to compare floating point numbers, and stick to bash, you can use bc and do
if [[ $(bc <<< "$name3 <= $name4") == 1 ]]; then
or you write your complete shell script in zsh instead of bash, and get floating point arithmetic for free:
if (( name3 >= name4 )); then # zsh only!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With