问题描述
我正在尝试检查主机是否已启动并做出相应的响应。这有效:
if ! ping -c 1 -W 1 "$_target_computer_ip"; then
wakeonlan -i "$_target_computer_subnet" "$_target_computer_mac"
fi
但这并没有达到预期的效果:
host_pc_status() {
ping -c 1 -W 1 "$_target_computer_ip"
return $?
}
if [ ! "$( host_pc_status )" ]; then
wakeonlan -i "$_target_computer_subnet" "$_target_computer_mac"
fi
条件总是评估为真。这是因为 $ ( host_pc_status )
返回 ping 的标准输出,考虑到命令替换将命令替换为其标准输出,这是有道理的。
我如何让 host_pc_status() 只返回退出代码而不添加额外的条件?我的目标是编写尽可能易读的代码,因为我忘记了事情,而且要简单。
check_host_pc_status() {
ping -c 1 -W 1 "$_target_computer_ip"
_host_pc_ping_exit_code=$?
}
check_host_pc_status
if [ "$_host_pc_ping_exit_code" ]; then
wakeonlan -i "$_target_computer_subnet" "$_target_computer_mac"
fi
以下是一种简单的方法,但如果我的函数和变量为我解释我的代码,我更喜欢它:
ping -c 1 -W 1 "$_target_computer_ip" || \
wakeonlan -i "$_target_computer_subnet" "$_target_computer_mac"
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)