Pietro
Pietro

Reputation: 13222

How can I make the changes done by a shell script permanent?

How can I make the changes done by a shell script be permanent, even when the script terminates?

E.g.: script.sh

#!/bin/sh
cd dir2
pwd

Using this script:

cd dir1
script.sh
pwd

I get:

dir2
dir1

How can I stay in dir2 after the script terminates?

Upvotes: 3

Views: 718

Answers (1)

Hln
Hln

Reputation: 767

script.sh is executed in a child process ("subshell"), and changing working directory in a child process doesn't affect working directory of parent process.

To change directory with something that looks like "a script", you have at least 3 possibilities:

  • setting an alias; suitable for interactive work with shell; not your case, as far as I understand;
  • writing a shell function instead of script.sh, see an example here;
  • run script.sh in the current process using source or simply .

Example of the last:

source script.sh

or

. script.sh

More on source command here.

And there is another really weird possibility, see here: change working directory of caller. Nevertheless, don't take it too serious, consider like a very geeky joke for programmers.

Upvotes: 3

Related Questions