Search code examples
linuxbashtop-command

Running a script with top command in the background


I have a script that basically prints that output of top -n1 to a file every second

In its simplest form:

while [ 1 ] ; do
   top -n1
   sleep 1
done

If I run my secript like:

./my_script.sh > out.log

it runs fine

If I run it in the background:

./my_script.sh > out.log &

Then it give me Stopped(SIGTTOU) error. From other Q/As I found that top is trying to read from the stdin, and when run in the background there is no stdin.

How can I achieve logging of top into a file as a background task?


Solution

  • You need to write top to file, and that in a loop..

    #!/bin/bash
    while [ 1 ] ; do
       top -b -n 1 > top.txt
       sleep 1
    done
    

    or

    #!/bin/bash
    while :
    do
      top -b -n 1 > top.txt
      sleep 1
    done