Reputation: 311
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)
Upvotes: 4
Views: 14033
Reputation: 897
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.
Upvotes: 8
Reputation: 241808
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
Upvotes: 2