Alby
Alby

Reputation: 5742

How can I cd into a directory using a script?

For example, let's say I have a directory called tmp and I am on the home directory

$pwd
/my/home/directory/
$ls
tmpdir

and I have a tmp.sh that cds into the "tmp" directory

#!/bin/bash
cd tmp

and I run the script using:

$sh tmp.sh

after running this script, I am still in my home directory.

1) I want to understand why this doesn't work thoroughly(I just roughly know it has to do with children process that is independent of parent process(is this even right?)) and

2) how can I go about accomplishing this task(being end up in the directory that a script cd-ed in upon the completion of execution of the script)?

Upvotes: 3

Views: 4230

Answers (4)

mtk
mtk

Reputation: 13709

That's the working directory of your shell. When you execute a script a new shell is created for your script. You are changing the present working directory for rest of your code and not the parent shell.

2) how can I go about accomplishing this task(being end up in the directory that a script cd-ed in upon the completion of execution of the script)?

To accomplish this you can && you script. So if the script executes successfully then only you end up in the new directory as

./tmp.sh && cd <to_your_directory>

You should also go through the unix.se post - Why cd is not a program? for better understanding.

Upvotes: 4

DrC
DrC

Reputation: 7698

1) The current working directory, cwd, is part of the state of a process. When a shell script starts, it is a new process so it has its own cwd. Any commands in the script's shell only impact that process's cwd.

2) Provided your script doesn't otherwise produce output, you could have your script output the directory you want and have a shell function/alias that invokes the script and changes to the output location. Something like

cd `script`

Upvotes: 0

that other guy
that other guy

Reputation: 123410

The short answer is that scripts run in a separate process, and changing the current directory in one process does not affect other processes. The same is true for e.g. setting variables (see here for some fascinating bugs this can cause).

To make it work, you can either source your script with source tmp.sh to run the script as if you had typed it on your prompt. To make it more convenient, you can add a function in your ~/.bashrc :

foo() { 
   cd somewhere
}

or an alias with

alias foo="cd somewhere"

Both will then allow you to cd somewhere when you run foo (from the next login).

Upvotes: 2

Udo Klein
Udo Klein

Reputation: 6882

1) When you run a shell script it runs in a new instance of the shell. Once this shell terminates you are still in the old untouched version of the shell. That is from the outside the shell script is just some piece of code.

2) There is no really good solution. I would do

sh tmp.sh && cd /tmp

Upvotes: 2

Related Questions