11

I have this script

#!/bin/bash
cd /home/user/somedir
pwd

it works as expected, but I would like this script to transport me to /home/user/somedir, but I stay in the same dir.

How to write script that will transport me (in gnome-terminal) to /home/user/somedir?

muru
  • 193,181
  • 53
  • 473
  • 722
UAdapter
  • 17,157
  • 38
  • 78
  • 102
  • 2
    possible duplicate of [Why doesn't "cd" work in a shell script?](http://askubuntu.com/questions/481715/why-doesnt-cd-work-in-a-shell-script) – muru Dec 04 '14 at 18:15

2 Answers2

16

You need to source your script. If not it will be run in a separate subshell, changing the working directory of the subshell but not of the shell you run it in.

To source it :

. myfile.sh

or

source myfile.sh

You can read more here

danjjl
  • 6,335
  • 4
  • 31
  • 49
  • I was just going to add that.... UAdadapter if you were running the shelll script like sh myfile.sh or ./myfile.sh it would run as danjil described. Either of danjil's options should work for you. – itnet7 Dec 01 '11 at 12:21
4

Use exec bash at the end

A bash script operates on its current environment or on that of its children, but never on its parent environment.

However, this question often gets asked because one wants to be left at a bash prompt in a certain directory after the execution of a bash script from another directory.

If this is the case, simply execute a child bash instance at the end of the script:

#!/bin/bash
cd /home/user/somedir
exec bash
Serge Stroobandt
  • 4,838
  • 1
  • 45
  • 58