Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I change directories using "cd" in a script?

Tags:

bash

I'm trying to write a small script to change the current directory to my project directory:

#!/bin/bash cd /home/tree/projects/java 

I saved this file as proj, added execute permission with chmod, and copied it to /usr/bin. When I call it by: proj, it does nothing. What am I doing wrong?

like image 587
ashokgelal Avatar asked Nov 01 '08 02:11

ashokgelal


People also ask

How do I change the directory in a script?

To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.

Why directory Change can't be made in a separate process?

Why we can't create a process which change the current working dir. Just like cd command does? You can't change the current working directory of another process. cd is a builtin command because an external executable can't change the cwd of the shell.


2 Answers

Shell scripts are run inside a subshell, and each subshell has its own concept of what the current directory is. The cd succeeds, but as soon as the subshell exits, you're back in the interactive shell and nothing ever changed there.

One way to get around this is to use an alias instead:

alias proj="cd /home/tree/projects/java" 
like image 154
Greg Hewgill Avatar answered Oct 22 '22 02:10

Greg Hewgill


You're doing nothing wrong! You've changed the directory, but only within the subshell that runs the script.

You can run the script in your current process with the "dot" command:

. proj 

But I'd prefer Greg's suggestion to use an alias in this simple case.

like image 36
Adam Liss Avatar answered Oct 22 '22 03:10

Adam Liss