简体   繁体   中英

GNU screen - execute another command only after program has run

I've been looking for an answer to this problem for a while but can't come up with the solution. I think it's more complicated than it looks!

I am trying to use GNU screen to run a lengthy program on a remote server (runs over several days), and then generate a text file to say it's finished only after that program has finished running. I have tried the following command:

screen -d -m <long program> && echo 'finished' >> finished.txt

It's essential that the screen detaches immediately because this will be an automated process using the watch command in bash. But unfortunately the command above generates the text file as soon as the command goes in (I'm guessing it's counting successful execution of screen as the signal to proceed onto the next command. I have tried various other arrangements, including

screen -d -m "<long program> && echo 'finished' >> finished.txt

But in this case it doesn't even seem to generate a screen at all, nor does it generate the text file. Note also that modifying the long program to generate this text file doesn't appear to be an option.

Are there any other workarounds? Any help would be greatly appreciated!

screen can only take a single command and its arguments as its own final arguments. <long program> && echo 'finished' >> finished.txt , unfortunately, is a shell command and cannot be passed directly to screen . You can, however, embed it in a string and pass it as a single argument to the shell's -c option:

screen -d -m sh -c '<long program> && echo "finished" >> finished.txt'

Depending on what exactly <long program> is, you may need to be very careful about how any quoting is escaped.

chepner's answer is a good solution.

Another solution, which might be a bit easier to manage, is to create a shell script that you invoke via screen rather than constructing a long shell command on the fly.

For example, you might create a script called run-long-command that looks something like this (don't forget to chmod +x it):

#!/bin/sh

if long-command ; then
    echo Finished > finished.txt
else
    echo Failed > finished.txt
fi

and then submit it to screen like this:

screen -d -m ./run-long-command

Note that the script is a little fancier than the shell command; it reports whether long-command passed or failed. Using a script also means that you have a record of what you did in the script file, not just in your shell command history.

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