I use virtualenv to switch between environments "1.0" and "2.0".
I use screen to manage terminals.
When I work on one environment I want all new screen windows to start with this environment.


Can bash instruct screen to set environment variable on new shell instances, so I could make an alias similar to this one:

alias one='export PRJCT=1.0; screen-magic-setenv PRJCT=1.0; workon 1.0'
alias two='export PRJCT=2.0; screen-magic-setenv PRJCT=2.0; workon 2.0'

and afterwards in ~/.bashrc call:

[[ -z $PRJCT ]] || workon $PRJCT # switch to project if set

I know I can command screen to set environment variable on new shells like below but it doesn't help as it won't work in an alias:

:setenv PRJCT

If I understand correctly, your problem is you cannot find a way to use a shell alias to interact with screen directly. Instead, you can send commands to a running screen using -X, including setenv of course, e.g.:

$ screen -list
There are screens on:
    25216.pts-45.antiriad      (Attached)

$ screen -S 25216 -X setenv PRJCT 2.0

The variable is then set, and will be inherited by child shells from that point on, exactly as with :setenv. If you use -S to set sensible distinct session names your task may be easier. The variable STY holds the current screen session.

If you run just screen -X setenv PRJCT 2.0 within a screen session, omitting -S, it will apply to that screen instance.

alias one='export PRJCT=1.0; screen -X setenv PRJCT 1.0; workon 1.0'
  • 1
    Only tested it now and as expected, worked like a charm. Thanks mate. – cprn Sep 25 '14 at 16:55
  • Isn't there a permanent way to always have the environment variables when a new screen is created? – André Yuhai Sep 21 '20 at 15:34
  • 1
    @AndréYuhai - You can use setenv in the configuration to do this. Instead though, I use a test like if [ "$TERM" = "screen" ] in my .bashrc as it's is more flexible. – mr.spuratic Sep 30 '20 at 17:52

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.