Bash脚本无法在Shell中运行

时间:2018-03-19 13:40:16

标签: bash shell zabbix

我一直在尝试为Zabbix实现警报脚本。由于某些原因,Zabbix尝试在Shell中运行脚本,而脚本是用Bash编写的。

#!/bin/bash

# Slack incoming web-hook URL and user name
url='https://hooks.slack.com/services/this/is/my/webhook/'             # example: https://hooks.slack.com/services/QW3R7Y/D34DC0D3/BCADFGabcDEF123
username='Zabbix Notification System'

## Values received by this script:
# To = $1 (Slack channel or user to send the message to, specified in the Zabbix web interface; "@username" or "#channel")
# Subject = $2 (usually either PROBLEM or RECOVERY/OK)
# Message = $3 (whatever message the Zabbix action sends, preferably something like "Zabbix server is unreachable for 5 minutes - Zabbix server (127.0.0.1)")

# Get the Slack channel or user ($1) and Zabbix subject ($2 - hopefully either PROBLEM or RECOVERY/OK)
to="$1"
subject="$2"

# Change message emoji depending on the subject - smile (RECOVERY/OK), frowning (PROBLEM), or ghost (for everything else)
recoversub='^RECOVER(Y|ED)?$'
if [[ "$subject" =~ ${recoversub} ]]; then
        emoji=':smile:'
elif [ "$subject" == 'OK' ]; then
        emoji=':smile:'
elif [ "$subject" == 'PROBLEM' ]; then
        emoji=':frowning:'
else
        emoji=':ghost:'
fi

# The message that we want to send to Slack is the "subject" value ($2 / $subject - that we got earlier)
#  followed by the message that Zabbix actually sent us ($3)
message="${subject}: $3"

# Build our JSON payload and send it as a POST request to the Slack incoming web-hook URL
payload="payload={\"channel\": \"${to//\"/\\\"}\", \"username\": \"${username//\"/\\\"}\", \"text\": \"${message//\"/\\\"}\", \"icon_emoji\": \"${emoji}\"}"
curl -m 5 --data-urlencode "${payload}" $url -A "https://hooks.slack.com/services/this/is/my/web/hook"
~

当我使用'bash slack.sh'在本地运行脚本时,它发送一个空通知,我在Slack中收到。 当我使用'sh slack.sh'在本地运行脚本时,我收到以下错误。

slack.sh: 19: slack.sh: [[: not found
slack.sh: 21: [: unexpected operator
slack.sh: 23: [: unexpected operator
slack.sh: 34: slack.sh: Bad substitution

感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

你的shebang是错的。

# !/bin/bash

删除第一个空格。

答案 1 :(得分:0)

在调用脚本时,您似乎使用代替

使用

bash script.sh

chmod +x script.sh
/full/path/to/script.sh

注意:

所以现在,你知道这个问题。一种解决方案是将脚本更改为POSIX shell或搜索如何强制zabbix处理bash脚本

答案 2 :(得分:0)

未能说服Zabbix使用bash执行脚本,您必须放弃正则表达式匹配(expr命令,奇怪的是,不支持任何形式的更改,意味着它的正则表达式只能识别常规语言的子集:

# if RECOVER(Y|ED)$ were a valid POSIX basic regular expression,
# you could use
#
#   if expr "$subject" : "$recoverysub"; then
#
# but it is not, so you need...
if [ "$subject" = RECOVERY ] || [ "$subject" = RECOVERED ]; then

答案 3 :(得分:0)

您可以通过添加

强制脚本与bash一起运行
#! /bin/bash

if [ -z "$BASH" ]
then
    exec /bin/bash "$0" "$@"
fi
...