1

Running a command in a screen and detaching is quite simple.

screen -S test -d -m echo "output of command that runs forever"

However I would also like to pipe all the output to a file for logging, how can run the following in a screen and detach.

echo "output of command that runs forever" &> output.log

Edit:

Just to clarify, I need this for a script so simple starting a screen and doing running the command and detaching is not an option.

4

screen -dmS workspace; screen -S workspace -X stuff $'ps aux > output-x\n'

I first create a detached session with the -d switch, I called my session workspace. I then send my command to the same session with -X stuff, I am using $'', but you could also use double quotes, but have to do a control M instead of a \n, which I don't like so I normally use the method I described above.

After this piece of code runs, you will find the output-x with the list of processes, and also if you do a:

screen -ls

you will see the session has been detached.

Since you said you are going to be running a script. You might want to have your script search for a detached session (I am using workspace), and if it exists send commands to that pre-existing session, instead of making a new session every time "screen -dmS sessionName" is ran, example is below:

    #!/bin/bash
    if ! ( screen -ls | grep workspace > /dev/null); then
       screen -dmS workspace;
    fi
    screen -S workspace -X stuff $'ps aux > output-x\n'
  • Thank you very much, this helped. On slower vms I did have to add a sleep between the two commands for it to work reliably. – Fabian Barkhau Jan 29 '16 at 15:15
  • does this work if we wanted to monitor serial port, for e.g. screen /dev/ttyUSB0? – deostroll Jul 28 at 2:36
1

You can wrap your command in an extra bash (or your actual shell) call and make redirection there:

$ screen -dm bash -c 'echo hello > ./out' ignoreme_arg
$ cat ./out
hello

Here ignoreme_arg stands for called bash $0 argument.

0

You can use the disown or nohup

usage: How to monitor WGET download progress after closing SSH session

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.