我正在寻找在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

其他回答

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

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

上面的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循环来模拟基本的功能:

while :; do clear; your_command; sleep 2; done

这将永远循环,清除屏幕,运行命令,并等待两秒钟-基本的watchyour_command实现。

你可以更进一步,创建一个watch.sh脚本,它可以接受your_command和sleep_duration作为参数:

#!/bin/bash
# usage: watch.sh <your_command> <sleep_duration>

while :; 
  do 
  clear
  date
  $1
  sleep $2
done

如果手表不想通过安装

brew install watch

有另一个类似的/复制版本,安装和工作完美为我

brew install visionmedia-watch

https://github.com/tj/watch

试试这个:

#!/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