Use script to monitor command output question? (like Linux watch)

Hi

I want to write a script, help me to monitor command output.

This script like Linux "watch" command.

Below is my script:

[root@host scripts]# cat watch.sh 
#!/bin/bash

while true
do
        clear
        echo "command: $*"
        ( $* )
        sleep 2
done

Then I run this script below

[root@station54 scripts]# ./watch.sh ls -l

Output like below

Interval 2 sec, Command: ls -l
total 40
drwxr-xr-x 2 root root 4096 Sep 27 21:34 aaa
-rw-r--r-- 1 root root    0 Sep 27 21:34 bbb
-rw-r--r-- 1 root root    0 Sep 27 21:34 ccc
-rw-r--r-- 1 root root    0 Sep 27 21:34 ddd
-rw-r--r-- 1 root root    0 Sep 27 21:34 eee
-rw-r--r-- 1 root root    0 Sep 27 21:34 fff
-rw-r--r-- 1 root root    0 Sep 27 21:34 ggg
-rwxr--r-- 1 root root   93 Sep 27 21:36 watch.sh

Then I run this script again "with pipe line and grep." , and every thing wrong...(screen not clear ...etc)

[root@station54 scripts]# ./watch.sh ls -l | grep eee

BUT Output like below

[root@station54 scripts]# ./watch.sh ls -l | grep eee
-rw-r--r-- 1 root root    0 Sep 27 21:34 eee
-rw-r--r-- 1 root root    0 Sep 27 21:34 eee  
-rw-r--r-- 1 root root    0 Sep 27 21:34 eee 
.
.

I except output like below

Interval 2 sec, Command: ls -l | grep eee
-rw-r--r-- 1 root root    0 Sep 27 21:34 ddd

How to complete this ....? please give me a hand.

Thanks,

Something like this?

#!/bin/bash
while true
do
        cmd="$*"
        echo "Intervel 2 sec, Command: $*"
        eval $cmd
        break
done
 
[orange@bt ~/aen]./run "ls -l | grep run"
Intervel 2 sec, Command: ls -l | grep run
-rwxr-xr-x 1 orange orange 126 Sep 27 19:43 run

--ahamed

1 Like

Hi ahamed,

Thanks for your help!!

That's actually I want... :slight_smile:

So, the KEY POINT is "eval".

Thanks again !