4

I'm trying to write a bash script to create a screen (software) session with a specific set of windows, and cd to specific directories on each one.

Here is the script I have so far:

#!/bin/bash killall screen; screen -AmdS work; screen -S work bash -c "cd myDir"; 

The problem is that I can't seem to change directories on that session. After running this script, I run $ screen -r and the current directory is still my default directory (~/).

(I've tried changing the cd command to touch myFile and the file is there after I run the script)

2
  • 2
    If you try bash -c "cd myDir" in your terminal, you'll see that it doesn't change directories. Use the screen command (not shell command) chdir to change directories, then open a new shell and it will start in that directory Commented Dec 9, 2016 at 20:44
  • 1
    Well -- it changes directories, but it changes the directory of the new shell you started with the bash command, not the directory of the shell/program that ran it. And since that new shell is exiting as soon as it finishes running the script it was passed with bash -c... Commented Dec 9, 2016 at 20:55

2 Answers 2

8

Try the following, it will open a new screen session with a bash which will change the directory and open a new bash with this directory as current:

screen -S work bash -c 'cd myDir && exec bash' 

Adding -d -m to run it in detached mode. And after reattaching you will be in myDir:

screen -S work -d -m bash -c 'cd myDir && exec bash' 

Better solution

The following code will create a detached screen with 3 screens each running myCommand1/2/3 in directory myDir1/2/3.

cd myDir1 screen -S work -d -m screen -S work -X exec myCommand1 screen -S work -X chdir myDir2 screen -S work -X screen screen -S work -X exec myCommand2 screen -S work -X chdir myDir3 screen -S work -X screen screen -S work -X exec myCommand3 cd - 

Note the last cd - that will return you back to your original working directory.

Finally just use screen -r work to attach your running screen session.

Sign up to request clarification or add additional context in comments.

2 Comments

cd mydir && exec bash avoids leaving the parent process sitting in memory
@CharlesDuffy even better, thanks.. i'll update the answer with exec
2

You can save the command line you want to run (including the final newline) into a register and paste it into the screen input:

screen -S work -X register c $'cd myDir\n' screen -S work -X paste c 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.