#!/usr/bin/env python3 # -*- coding: utf-8 -*- r'''把 watchdog.sh 里裸用的 $BUILT 换成 ${BUILT:-0}。 背景: watchdog.sh 开头有 `set -u`(未定义变量直接报错退出)。 我给 restart_tunnel() 里加了 `write_state 0 0 "$BUILT"`, 但这个函数定义在 `BUILT=$(read_state built 0)` **之前**, 函数被调用时 BUILT 还不存在 -> 报 "BUILT: 未绑定的变量"。 这么写一次就够,然后用 bash -n 和实跑验证。 ''' from pathlib import Path WD = Path("/root/lanremote-relay/watchdog.sh") def main() -> int: text = WD.read_text(encoding="utf-8") old = 'write_state 0 0 "$BUILT"' new = 'write_state 0 0 "${BUILT:-0}"' count = text.count(old) if count: text = text.replace(old, new) WD.write_text(text, encoding="utf-8", newline="\n") print(" 替换 %d 处" % count) print() print(" 现在所有 BUILT 用法:") for index, line in enumerate(WD.read_text(encoding="utf-8").splitlines(), 1): if "BUILT" in line: mark = "" if "$BUILT" in line and "${BUILT:-0}" not in line: mark = " <-- 检查这里" print(" %3d: %s%s" % (index, line.strip(), mark)) return 0 if __name__ == "__main__": raise SystemExit(main())