Ubuntu – Execute command on Gnu Screen attachment

gnu-screen

Is it possible for GNU Screen to detect when a session has been attached and to run a command? (The command will be a shell script that I wrote)

Thanks.

Best Answer

What exactly are you trying to do? These probably don't exactly answer your question but you might be able to adapt them to your needs:

You could create a script called screenr that will reattach a screen session after first executing your script in that session.

#!/bin/bash
screen -X exec /command/to/run
screen -r $@

Another idea might be to put something in your .bashrc to check if you're running screen and then execute a command. That will run whenever you start a new screen session or create a new shell in screen but it won't run if you attach an already running screen session.

if [ $TERM = "screen-256color-bce" ]; then
    /command/to/run
fi

Edit: After seeing your other question it looks like the screen command setenv might be what you want, but it only sets environment variables for new shells started in screen, not already running ones.

screen -X setenv DISPLAY $DISPLAY