为什么 watch 在脚本中超时调用时不显示任何内容?

Rag*_*dda 9 bash watch macos

当我运行此脚本时,它不会watch在屏幕上显示输出,并且不会在 5 秒后超时。

§ cat script.sh
#!/bin/bash
timeout 5s watch -n 1 ps
Run Code Online (Sandbox Code Playgroud)

这是我运行脚本时在屏幕上看到的:

在此处输入图片说明

但是,直接在终端中运行脚本的内容会按预期工作:即,

§ timeout 5s watch -n 1 ps
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

wyr*_*yrm 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
Run Code Online (Sandbox Code Playgroud)

并且watch需要写入终端才能完成所有花哨的 ANSI 技巧。

如果您想查看实际效果,请尝试以下操作:

$ script -c 'timeout --foreground 5s watch -n 1 ps'
$ less typescript
Run Code Online (Sandbox Code Playgroud)