1

I have a bash script where I can pipe in output from another application into the below script. But I think I have an incorrect logic for testing if the message is empty or not. If its empty I want it to do nothing, but if it detects the word "error" in the string, it should run another function.

What am I doing wrong in my logic?

I'm getting too many arguments on the 3rd to the last line, most likely due to the message being empty.

message=$( cat )

if [ -n "${message// /}" ]; then
  #execute if the the variable is not empty and contains non space characters
  message="\`\`\` ${message} \`\`\`"
else
  #execute if the variable is empty or contains only spaces
  message=""
fi

sendX() {
.....
}

if  [ -z "$message" ]; then
        echo "Please pipe a message to me!"
else
        sendX
fi

sendAlert() {
......
}

checkword="error"

echo $message

if [ $message =~ $checkword ]; then  <---- Error: too many arguments
 sendY
fi
0
4

You're getting a "too many arguments" error since [ ... ] does not understand the =~ operator (used in bash for regular expression matching). Since [ ... ] does not understand the operator, it is treated as a string. You then have [ ... ] with three strings inside it, and they don't fulfil the semantic requirements for a proper test, which is why bash errors out at this point.

In bash, you would use =~ inside of [[ ... ]].

However, what I assume you'd like to do in that test is to see whether $message contains $checkword as a substring. This could also be done with

[[ "$message" == *"$checkword"* ]] && sendY

or with case ... esac:

case $message in
    *"$checkword"*) sendY
esac

This way you don't have to worry about $checkword containing characters that may be special in regular expressions.

You also need to double quote $message in echo $message, or you may get unexpected output if $message contains filename globbing characters like *.

Related:


You could also use this instead of the first operation in the script:

case $message in
    *[!\ ]*) # contains non-space
        message='``` '"$message"' ```' ;;
    *)       # contains nothing or only spaces
        message=
esac

Using case ... esac in both places would make your script (at least the bits that you have shown) portable to any sh-like shell.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.