变量多次引用问题!

秋风啸落叶 2017-09-01 04:52:50
[code=text][function get_pid_int
{
echo `netstat -lntp | awk '{print $0, $4}' | grep :7180$ | awk '{print $7}' | awk -F '/' '{print $1}'`
}

sleep_number="30s"
pid_name="cloudera-scm-server"
Port="7180"
#pid_name="httpd"
#Port="80"
restart_command="systemctl restart $pid_name"
http_code_cmd=$(netstat -lntp | awk '/^tcp/{print $4}' | grep -q ":$Port$";echo $?)
pid_old=$(get_pid_int)
#echo $pid_old
# 当服务已经启动时,做重启操作
if [ $http_code_cmd -eq 0 ]
then
echo "$pid_name 重新启动中......"
$restart_command
sleep 5s
if [ $http_code_cmd -ne 0 ]
then
for (( i=1; i<= 30; i++))
do
sleep $sleep_number
if [ $http_code_cmd -eq 0 ]
then
break;
fi
done
fi
pid_new=$(get_pid_int)
if [ $result -eq 0 ] && [ x"$pid_old" != x"$pid_new" ];then echo "重启 $pid_name 成功!";exit 0;
else
echo "重启 $pid_name 失败!因为新端口号 $pid_new 和就端口号 $pid_old 一致!"
exit
fi
fi
/code]
现在问题是if和for语句类的http_code_cmd获取的变量值都是第一次赋值得到的。现在请问怎么在if循环内多次对调用http_code_cmd所执行的新的值?
...全文
227 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
秋风啸落叶 2017-09-01
  • 打赏
  • 举报
回复
谢谢!!受教了!
代码誊写工 2017-09-01
  • 打赏
  • 举报
回复
把所有的
$http_code_cmd
替换为
$(netstat -lntp | awk '/^tcp/{print $4}' | grep -q ":$Port$";echo $?)
就达到你要的目的。 嫌多就
http_code_cmd="netstat -lntp | awk '/^tcp/{print \$4}' | grep -q \":\$Port$\""
if eval http_code_cmd; then dosomting; fi
#没有必要再[ $(echo $?) -eq 0 ], if实际上就是通过“[”的“$?”来判断是执行then还是else(或退出)
...
建议用这种形式
netstat -lnpt | grep -qP ":${Port} " && {
    #如果找到就执行
}
netstat -lnpt | grep -qP ":${Port} " || {
    #如果没找到就执行
}
netstat -lnpt | grep -qP ":${Port} " && {
    #如果找到就执行
} || {
    #如果没有找到就执行
}
的组合,除了好看些之外,性能比if test好不少

18,777

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 专题技术讨论区
社区管理员
  • 专题技术讨论区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧