Search code examples
linuxbashscriptinggnu-screen

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!


Solution

  • 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.