随着即时通讯的发展,大量的报警媒介已经从以往的邮件转为钉钉,企业微信等聊天工具。当我使用shell脚本来监控
Keepalived
的时候,在给curl传递变量的时候无法生效,经过查找相关资料有所了解并加以解决,解决方案如下:
解决方案
错误shell代码:
#!/bin/bash
#
notify() {
#mailsubject="$(hostname) to be $1, vipIP 切换成功 "
local mailsubject="$(date +'%F %T'):$(hostname) to be $1, vipIP 切换成功 "
local mailbody="$(hostname) 修改成 $1 模式"
#local mailbody="$(date +'%F %T'): vrrp transition, $(hostname) changed to be $1"
#echo "$mailbody" | mail -s "$mailsubject" $contact
curl 'https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxx' \
-H 'Content-Type: application/json' \
-d '{"msgtype": "text",
"text": {
"content": "测试$mailsubject"
}
}'
}
case $1 in
master)
notify master
;;
backup)
notify backup
;;
fault)
notify fault
;;
*)
echo "Usage: $(basename $0) {master|backup|fault}"
exit 1
;;
esac
结果:
image-20210723144722549
通过测试的结果来看,这是典型的没有正确传变量值。通过查找相关资料确认,是因为shell脚本的单引号字符串有所限制,单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的。然后在我们这个脚本中,发送钉钉消息,需要传递变量值内容的刚好是在单引号中,也就导致了无法正常传递。那么怎么解决这个问题呢?既然找到问题了,那么解决也简单,我们需要将符号转义即可。方法如下👇:
- 在单引号周围添加双引号
curl 'https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxx' \
-H 'Content-Type: application/json' \
-d '{"msgtype": "text",
"text": {
"content": "'"测试$mailsubject"'"
}
}'
}
那么正确的代码如下:
#!/bin/bash
#
notify() {
#mailsubject="$(hostname) to be $1, vipIP 切换成功 "
local mailsubject="$(date +'%F %T'):$(hostname) to be $1, vipIP 切换成功 "
local mailbody="$(hostname) 修改成 $1 模式"
#local mailbody="$(date +'%F %T'): vrrp transition, $(hostname) changed to be $1"
#echo "$mailbody" | mail -s "$mailsubject" $contact
curl 'https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' \
-H 'Content-Type: application/json' \
-d '{"msgtype": "text",
"text": {
"content": "'"测试 ${mailsubject}\n ${mailbody}"'"
}
}'
}
case $1 in
master)
notify master
;;
backup)
notify backup
;;
fault)
notify fault
;;
*)
echo "Usage: $(basename $0) {master|backup|fault}"
exit 1
;;
esac
结果:
image-20210723163740961
从最后的结果能看出来,已经成功的将值传过来了,完事!
参考链接
Original: https://www.cnblogs.com/98record/p/ru-he-zaishell-jiao-ben-zhong-chuan-bian-liang-de.html
Author: 自在拉基
Title: 如何在shell脚本中传变量的值传给curl
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/586086/
转载文章受原作者版权保护。转载请注明原作者出处!