我正在寻找在Mac OS x上复制Linux 'watch'命令的最佳方法。我想每隔几秒钟运行一个命令,使用'tail'和'sed'对输出文件的内容进行模式匹配。

我在Mac电脑上最好的选择是什么?不下载软件能做到吗?


当前回答

上面的shell可以做到这一点,你甚至可以将它们转换为别名(你可能需要包装一个函数来处理参数):

alias myWatch='_() { while :; do clear; $2; sleep $1; done }; _'

例子:

myWatch 1 ls ## Self-explanatory
myWatch 5 "ls -lF $HOME" ## Every 5 seconds, list out home directory; double-quotes around command to keep its arguments together

Homebrew也可以从http://procps.sourceforge.net/:上安装手表

brew install watch

其他回答

上面的shell可以做到这一点,你甚至可以将它们转换为别名(你可能需要包装一个函数来处理参数):

alias myWatch='_() { while :; do clear; $2; sleep $1; done }; _'

例子:

myWatch 1 ls ## Self-explanatory
myWatch 5 "ls -lF $HOME" ## Every 5 seconds, list out home directory; double-quotes around command to keep its arguments together

Homebrew也可以从http://procps.sourceforge.net/:上安装手表

brew install watch

Linux上可用的watch命令在macOS上不存在。如果你不想使用brew,你可以将这个bash函数添加到你的shell配置文件中。

# execute commands at a specified interval of seconds
function watch.command {
  # USAGE: watch.commands [seconds] [commands...]
  # EXAMPLE: watch.command 5 date
  # EXAMPLE: watch.command 5 date echo 'ls -l' echo 'ps | grep "kubectl\\\|node\\\|npm\\\|puma"'
  # EXAMPLE: watch.command 5 'date; echo; ls -l; echo; ps | grep "kubectl\\\|node\\\|npm\\\|puma"' echo date 'echo; ls -1'
  local cmds=()
  for arg in "${@:2}"; do
    echo $arg | sed 's/; /;/g' | tr \; \\n | while read cmd; do
      cmds+=($cmd)
    done
  done
  while true; do
    clear
    for cmd in $cmds; do
      eval $cmd
    done
    sleep $1
  done
}

https://gist.github.com/Gerst20051/99c1cf570a2d0d59f09339a806732fd3

试试这个:

#!/bin/bash
# usage: watch [-n integer] COMMAND

case $# in
    0)
        echo "Usage $0 [-n int] COMMAND"
        ;;
    *)      
        sleep=2;
        ;;
esac    

if [ "$1" == "-n" ]; then
    sleep=$2
    shift; shift
fi


while :; 
    do 
    clear; 
    echo "$(date) every ${sleep}s $@"; echo 
    $@; 
    sleep $sleep; 
done

我从这里开始回答:

bash -c 'while [ 0 ]; do <your command>; sleep 5; done'

但你最好装个手表,因为这不是很干净……

或者,在你的~/。bashrc文件:(

function watch {
    while :; do clear; date; echo; $@; sleep 2; done
}