当我运行这个脚本时,它才不是watch
在屏幕上显示输出,并且才不是5秒后超时。
§ cat script.sh
#!/bin/bash
timeout 5s watch -n 1 ps
这是我运行脚本时在屏幕上看到的内容:
但是,直接在终端中运行脚本的内容可以按预期工作:即,
§ timeout 5s watch -n 1 ps
当从脚本调用时,到底发生了什么导致watch
屏幕上无法显示内容?
此外,在脚本中使用--foreground
选项可以使其按预期工作,但我不明白为什么。timeout
如果重要的话,这里是这些工具的版本:
§ bash --version
bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin19)
Copyright (C) 2007 Free Software Foundation, Inc.
§ watch -v
watch from procps-ng 3.3.12-dirty
§ timeout --version
timeout (GNU coreutils) 8.29
Copyright (C) 2017 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Padraig Brady.
答案1
timeout
从 shell 脚本运行时,其行为有所不同。该--foreground
选项强制默认的“交互”行为,即使是从脚本运行时也是如此。从联机帮助页:
--foreground
when not running timeout directly from a shell prompt, allow COMMAND to
read from the TTY and get TTY signals; in this mode, children of
COMMAND will not be timed out
并且watch
需要写入终端才能完成所有花哨的 ANSI 技巧。
如果您想查看实际效果,请尝试以下操作:
$ script -c 'timeout --foreground 5s watch -n 1 ps'
$ less typescript