Skip to content
Advertisement

Linux bash ‘[: -ge: unary operator expected’ error

#!/bin/bash


SubValue()
{


  romanvalue="${romanvalue}$2"
  decvalue=$(( $decvalue - $1 ))

}

if [ $decvalue -ge 1000 ] ; then
  SubValue 1000 "M"
elif [ $decvalue -ge 900 ] ; then
  SubValue 900 "CM"
elif [ $decvalue -ge 500 ] ; then
  SubValue 500 "D"
elif [ $decvalue -ge 400 ] ; then
  SubValue 400 "CD"
elif [ $decvalue -ge 100 ] ; then
  SubValue 100 "C"
elif [ $decvalue -ge 90 ] ; then
  SubValue 90 "XC"
elif [ $decvalue -ge 50 ] ; then
  SubValue 50 "L"
elif [ $decvalue -ge 40 ] ; then
  SubValue 40 "XL"
elif [ $decvalue -ge 10 ] ; then
  SubValue 10 "X"
elif [ $decvalue -ge 9 ] ; then
  SubValue 9 "IX"
elif [ $decvalue -ge 5 ] ; then
  SubValue 5 "V"
elif [ $decvalue -ge 4 ] ; then
  SubValue 4 "IV"
elif [ $decvalue -ge 1 ] ; then
  SubValue 1 "I"
fi

I tried this code and it gives many errors that

dectoroma.sh: line 13: [: -ge: unary operator expected dectoroma.sh: line 15: [: -ge: unary 
operator expected
dectoroma.sh: line 17: [: -ge: unary operator expected
dectoroma.sh: line 19: [: -ge: unary operator expected
dectoroma.sh: line 21: [: -ge: unary operator expected
dectoroma.sh: line 23: [: -ge: unary operator expected
dectoroma.sh: line 25: [: -ge: unary operator expected
dectoroma.sh: line 27: [: -ge: unary operator expected
dectoroma.sh: line 29: [: -ge: unary operator expected
dectoroma.sh: line 31: [: -ge: unary operator expected
dectoroma.sh: line 33: [: -ge: unary operator expected
dectoroma.sh: line 35: [: -ge: unary operator expected
dectoroma.sh: line 37: [: -ge: unary operator expected

could anyone help me to fix this problem please.

Advertisement

Answer

The source of the problem reported in the question is an empty decvalue as syme has already stated.

Considering the purpose of the script, it seems you attempted to write a recursive function. For this reason, i suggest you to follow the comment under your question by jww regarding debugging!

Moreover, you are encouraged to search for questions on recursive functions in bash on SO. There are excellent answers for factorial computations in bash.

Think about which quantities are “transported” and which are returned/compiled in the end.


If you are really stuck, you find 90% of the solution below.

#!/bin/bash
romanLetters(){
        local decvalue=$1
        local roman
        declare -i decvalue

        if [ $decvalue -ge 1000 ]; then
                romanvalue="M$(romanLetters $((decvalue - 1000)))"
                echo $romanvalue
        elif [ $decvalue -ge 900 ]; then
                romanvalue="CM$(romanLetters $((decvalue - 900)))"
                echo $romanvalue
        # ... and so on ...
        fi
}

echo "1900: $(romanLetters 1900)"
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement