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

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


当前回答

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

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

其他回答

使用MacPorts:

$ sudo port install watch

下面是这个答案的一个稍微改变的版本:

检查有效参数 在顶部显示日期和持续时间标题 将"duration"参数移动到第一个参数,这样复杂的命令可以很容易地作为其余参数传递。

使用它:

保存到~/bin/watch 在终端中执行chmod 700 ~/bin/watch使其可执行。 通过运行watch 1 echo“hi there”来尝试它

~ / bin /手表

#!/bin/bash

function show_help()
{
  echo ""
  echo "usage: watch [sleep duration in seconds] [command]"
  echo ""
  echo "e.g. To cat a file every second, run the following"
  echo ""
  echo "     watch 1 cat /tmp/it.txt" 
  exit;
}

function show_help_if_required()
{
  if [ "$1" == "help" ]
  then
      show_help
  fi
  if [ -z "$1" ]
    then
      show_help
  fi
}

function require_numeric_value()
{
  REG_EX='^[0-9]+$'
  if ! [[ $1 =~ $REG_EX ]] ; then
    show_help
  fi
}

show_help_if_required $1
require_numeric_value $1

DURATION=$1
shift

while :; do 
  clear
  echo "Updating every $DURATION seconds. Last updated $(date)"
  bash -c "$*"
  sleep $DURATION
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

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

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

试试这个:

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