繁体   English   中英

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 = $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

感谢您的协助。

你的shebang错了。

# !/bin/bash

删除该第一个空格。

您似乎在调用脚本时使用而不是

采用

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 "$0" "$@"
fi
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM