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 save
It is an old question, but I am really surprised I don't see this trick here
Instead of using cd you can use
export PWD=the/path/you/want
No need to create subshells or use aliases.
Note that it is your responsibility to make sure the/path/you/want exists.
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.
Create the script file
#!/bin/sh # file : /scripts/cdjava # cd /home/askgelal/projects/java
Then create an alias in your startup file.
#!/bin/sh # file /scripts/mastercode.sh # alias cdjava='. /scripts/cdjava'
For example, create a master aliases/functions file: /scripts/mastercode.sh
(Put the alias in this file.)
Then at the end of your .bashrc file:
source /scripts/mastercode.sh
Now its easy to cd to your java directory, just type cdjava and you are there.
to navigate directories quicky, there's $CDPATH, cdargs, and ways to generate aliases automatically
http://jackndempsey.blogspot.com/2008/07/cdargs.html
http://muness.blogspot.com/2008/06/lazy-bash-cd-aliaes.html
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5827311.html
The cd
is done within the script's shell. When the script ends, that shell exits, and then you are left in the directory you were. "Source" the script, don't run it. Instead of:
./myscript.sh
do
. ./myscript.sh
(Notice the dot and space before the script name.)
When you fire a shell script, it runs a new instance of that shell (/bin/bash
). Thus, your script just fires up a shell, changes the directory and exits. Put another way, cd
(and other such commands) within a shell script do not affect nor have access to the shell from which they were launched.