Shell script to change directory of terminal and open a second terminal

cd-commandshell-script

I am new to writing shell scripts and I am trying to write a script to CD to a folder where my programs are saved for one of my classes, then have a second terminal open that ssh's to a server used for testing the programs that I write. The problem is that I can not find a way to change the directory of the terminal shell to be where my programs are stored.

#!/bin/bash/
gnome-terminal -e "ssh user@foo.bar.edu";
cd /path/to/dir

the problem is that the working directory does not change after the script terminates (it stays as it was when the script was called). I tried calling it except with a '.' in front of the name of the script to get it to run in the current process but the second terminal never opened.

I tried to do the same thing as above except I replaced the third line with

gnome-terminal -e "cd /path/to/dir/";

so that way two terminals would open, but the terminal ment to CD to the path gave an error along the lines of "there was an error creating the child process for this terminal: failed to execute child process 'cd'"

can anyone help me figure out how to solve this problem?

Best Answer

Your first version first opens a gnome-terminal, waits until you close it and then changes to the new directory.

Your second version tries to run a command cd instead of a shell, however cd is not a real command but a shell builtin. (See type -a cd for that.)

The question is how gnome-terminal decides what directory to display. It will normally use the current working directory unless overridden by the --working-directory option.

Therefore you can use either:

cd /path/to/dir && gnome-terminal

or

gnome-terminal --working-directory=/path/to/dir

Have a look at man gnome-terminal for available options.

For the ssh part you have to decide whether you want to run you gnome-terminal on the local or remote side. To run it on the remote site you use:

ssh -X user@foo.bar.edu gnome-terminal --working-directory=/path/to/dir

for the local side you can use something like:

gnome-terminal -e "ssh -t user@foo.bar.edu bash -c 'cd /path/to/dir && bash -l'";
Related Question