3

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?

Pietro
  • 12,086
  • 26
  • 100
  • 193
  • 6
    The script is executed in a subshell. You could use a function instead of a script, which could be executed in the same shell. Would that be suitable? – Tom Fenech Apr 15 '15 at 22:16
  • If you can make an example as simple as mine, I can tell you. – Pietro Apr 15 '15 at 22:18
  • 8
    or "source" the script, and for heaven's sake, don't bother with the sh-bang. e.g: $ source script.sh OR $ . script.sh either of these execute the "script" in the current shell. – Marty McGowan Apr 15 '15 at 22:18
  • 2
    The function could be `cd_pwd () { cd dir2; pwd; }` then your script could be `cd dir1; cd_pwd; pwd`. – Tom Fenech Apr 15 '15 at 22:23
  • 1
    The working directory of the process that executes the `cd` is "permanently" changed (which is to say, until either the process terminates or another chdir is executed.) You need to reword the question. – William Pursell Apr 16 '15 at 14:51
  • 1
    Tom Fenech, and William Pursell comments are true: In UNIX, a process can not change its parent current working directory ever. Use a function, or and alias, or source the code containing the instructions from your shell as stated by Marty McGowan. – Antxon Apr 17 '15 at 05:59
  • @MartyMcGowan: If you can copy your comment as an answer, I would pick it. – Pietro May 04 '15 at 23:08

1 Answers1

3

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.

Community
  • 1
  • 1
Hln
  • 749
  • 5
  • 15