使用“手表"在 Bash 中重复运行一个函数? [英] Using "watch" to run a function repeatedly in Bash?

查看:12
本文介绍了使用“手表"在 Bash 中重复运行一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一个 Bash 脚本.我的 Debian 机器出现 WiFi 问题.我不是在这里询问原因,而是如何在 Bash 问题上使用创可贴.我的 WiFi 会随机掉线,通常每 12-15 分钟一次.我在这台服务器上使用 SSH,并且不想从物理服务器手动运行 ifdown wlan0ifup wlan0 (重新连接 WiFi).

This is my first Bash script. I have a WiFi issue with my Debian machine. I'm not here to ask about the cause, but rather how to put a band-aid on the issue with Bash. My WiFi will drop out at a random time, usually every 12-15 minutes. I use SSH on this server, and do not want to have to run ifdown wlan0 and ifup wlan0 (which reconnects the WiFi) manually from the physical server.

这个 Bash 脚本的作用是尝试连接 3 次.如果它失败了三遍,它就会放弃.否则,它将每三秒通过尝试 ping Google 来检查我的服务器是否已连接.

The function of this Bash script is to attempt to connect three times. If it fails three times, it will give up. Otherwise, every three seconds it will check whether or not my server is connected by attempting to ping Google.

#!/bin/bash

ATTEMPTS=1

function test_connection {
  ping -c 1 www.google.com
  local EXIT_CODE=$?
  if [ $EXIT_CODE -eq 0 ]
    then
      return true
    else
      return false
  fi
}
function reset_connection {
  ifdown wlan0
  ifup wlan0
  EXIT_CODE=$((EXIT_CODE+1))
}
function connection_test_loop {
  if [ $ATTEMPTS -ge  3 ]
    then
      echo CONNECTION FAILED TO INITIALIZE ... ATTEMPT $ATTEMPTS FAILED ... EXITING
      exit
  fi
  if ! [ test_connection ]
    then
      echo CONNECTION DROPPED ... ATTEMPTING TO RE-ESTABLISH CONNECTION ... ATTEMPT $ATTEMPTS
      reset_connection
  fi
}

test_connection
if [ $? ]
  then
    echo CONNECTION PRE-ESTABLISHED
    watch -n 3 connection_test_loop
  else
    echo CONNECTION FAILED TO INITIALIZE ... ATTEMPTING TO RESET CONNECTION ... ATTEMPT $ATTEMPTS
    reset_connection
    if [ $? ]
      then
        echo CONNECTION ESTABLISHED
        watch -n 3 connection_test_loop
      else
        echo CONNECTION FAILED TO INITIALIZE ... ATTEMPT $ATTEMPTS FAILED ... EXITING
        exit
    fi
fi

我已经隔离了我在使用此脚本时遇到的问题.在于用watch调用connection_test_loop函数.我一直找不到任何信息说明为什么它没有按预期执行并且每三秒运行一次函数.

I've isolated the issue I'm having with this script. It lies in calling the connection_test_loop function with watch. I've been unable to find any information as to why this isn't performing as expected and running the function every three seconds.

推荐答案

watch 可能不知道你的 connection_test_loop 函数.您可以尝试在下面添加 exporttest_connection 或许可以解决这个问题:

It's possible that watch is not aware of your connection_test_loop function. You can try adding an export below the test_connection to perhaps solve the issue:

test_connection
export -f connection_test_loop
...

http://linuxcommand.org/lc3_man_pages/exporth.html

当调用watch时,你可能需要这样的语法:

When calling watch, you may need this syntax:

watch -x bash -c connection_test_loop

这篇关于使用“手表"在 Bash 中重复运行一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆