Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "setup" screen using a bash script

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)

like image 585
Fábio Queluci Avatar asked Feb 05 '23 13:02

Fábio Queluci


1 Answers

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.

like image 71
martin.macko.47 Avatar answered Feb 08 '23 16:02

martin.macko.47