Bash 脚本不能 运行 在 Shell

Bash script can't be run in Shell

我一直在尝试为 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 =  (Slack channel or user to send the message to, specified in the Zabbix web interface; "@username" or "#channel")
# Subject =  (usually either PROBLEM or RECOVERY/OK)
# Message =  (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 () and Zabbix subject ( - hopefully either PROBLEM or RECOVERY/OK)
to=""
subject=""

# 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 ( / $subject - that we got earlier)
#  followed by the message that Zabbix actually sent us ()
message="${subject}: "

# 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

感谢您的协助。

你的shebang是错误的。

# !/bin/bash

删除第一个 space。

您似乎在调用脚本时使用了 instead

使用

bash script.sh

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

注:

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

无法说服 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

您可以通过添加

强制您的脚本 运行 和 bash
#! /bin/bash

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