How to execute a command in screen and detach?

Solution 1:

This is an easy one:

screen -d -m yourcommand

From the Screen User's Manual:

-d -m
Start screen in detached mode. This creates a new session but doesn’t attach to it. This is useful for system startup scripts.

Solution 2:

To run a single command in screen and detach, you may try:

screen -dm sleep 10

To run multiple commands, try:

screen -dm bash -c "sleep 10; myscript.sh"

Please note that when a program terminates, screen (per default) kills the window that contained it.

If you don't want your session to get killed after script is finished, add exec sh at the end, e.g.:

screen -dm bash -c 'sleep 5; exec sh'

To list all your sessions, try:

screen -list

Related: Start Unix screen, Run command, Detach.

Solution 3:

In order to start new session in background with name 'sleepy'

screen -S sleepy -dm sleep 60

In order to kill 'sleepy' session

screen -S sleepy -X quit      

Solution 4:

screen -dmS screen_session_name bash -c 'echo "doing stuff"; exec bash'

Solution 5:

it happen to me when I pressed control c (sig int) to exit my program. it exits all the way from all bash. so I found this to catch SIGINT. and prevent exit from last bash. (need to type exit to exit)

screen -dmS "screenNameHere" bash -c "trap 'echo gotsigint' INT; cd /mydir ; my_command_here;  bash"


example:

screen -dmS "status_updates" bash -c "trap 'echo gotsigint' INT; cd /opt/status_update ; forever index.js ;  bash"

I find it useful to use cron to run nodejs programs on startup. and to run the screen at boot time. in cron there are special events syntax @reboot event

to edit cron, execute:
crontab -e

then type
@reboot screen -dmS "screenNameHere" bash -c "trap 'echo gotsigint' INT; cd /mydir ; my_command_here;  bash"