3

I am having a problem with an example script that is given in the textbook 'Unix and System Administration Handbook'. The script is below... I am receiving an error that states logscript: line 8: [: 1: unary operator expected.

# The log level is set in the global variable LOG_LEVEL. The choices
# are, from most to least severe.  Error, Warning, Info, and Debug.

function logMsg {
    message_level=$1
    message_itself=$2

    if [ $message_level -le $LOG_LEVEL ]; then
            case $message_level in
                    0) message_level_text="Error";;
                    1) message_level_text="Warning";;
                    2) message_level_text="Info";;
                    3)message_level_text="Debug";;
                    *) message_level_text="Other"
    esac
    echo "${message_level_text}: $message_itself"
    fi
}


# Main program starts here
logMsg $1 $2

Any ideas as to why this error is showing up?

zzz2991
  • 153
  • 2
    Quote the variables i.e. use if [ "$message_level" -le "$LOG_LEVEL" ] ..check whether echo "$LOG_LEVEL" returns anything or not.. – heemayl Mar 23 '15 at 22:57
  • $LOG_LEVEL is not returning any value. I believe that the text mentions that, if LOG_LEVEL is set within the current bash session then the script will be able to reference it. Is this not right? – zzz2991 Mar 23 '15 at 23:05
  • 2
    When asking this sort of question, you need to include your operating system, your shell, and the way you are launching the function. – terdon Mar 23 '15 at 23:08

3 Answers3

2

That error is because LOG_LEVEL is not defined. You haven't given us any information at all about how you're running this function (nor what shell you are using or what operating system) but the error will go away if LOG_LEVEL is set.

For example:

$ foo=""; [ 1 -le $foo ] && echo yes
bash: [: 1: unary operator expected

While, if $foo is set:

$ foo="1"; [ 1 -le $foo ] && echo yes
yes
terdon
  • 242,166
0

As the comment says, please ensure your variable LOG_LEVEL is set, and call your script with an integer as the first argument (since the if is about to compare integers). Something like:

export LOG_LEVEL=3
./my_script 2 AnyMessage
apaul
  • 3,378
-3

You can try this:

if [[ $message_level -le $LOG_LEVEL ]]
Michael Mrozek
  • 93,103
  • 40
  • 240
  • 233