简体   繁体   中英

How can I run this command line in the background?

I have this

script -q -c "continuously_running_command" /dev/null > out

When I have the above command line running I can stop it by doing CTRL+C

However I'd like to run the above commandline in back ground so that I can stop it by doing kill -9 %1

But when I try to run this

script -q -c "continuously_running_command" /dev/null > out &

I get

[2]+  Stopped (tty output)       script -q -c "continuously_running_command" /dev/null 1>out

Question:

How can I run the above commandline in back ground?

In order to background a process with redirection to a file, you must also redirect stderr. With stdout and stderr redirected, you can then background the process:

script -q -c "continuously_running_command" /dev/null > out 2>&1 &

Fully working example:

#!/bin/bash

i=$((0+0))

while test "$i" -lt 100; do

    ((i+=1))
    echo "$i"
    sleep 1

done

Running the script and tail of output file while backgrounded:

alchemy:~/scr/tmp/stack> ./back.sh > outfile 2>&1 &
[1] 31779
alchemy:~/scr/tmp/stack> tailf outfile
10
11
12
13
14
...
100
[1]+  Done                    ./back.sh > outfile 2>&1

In the case of:

 script -q -c "continuously_running_command" /dev/null

The problem in in this case is the fact that script itself causes redirection of all dialog with script to FILE, in this case to /dev/null . So you need to simply issue the command without redirecting to /dev/null or just redirect stderr to out:

script -q -c "continuously_running_command" out 2>&1 &

or

script -q -c "continuously_running_command" /dev/null/ 2>out &

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM