792

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?

Tomerikoo
  • 12,112
  • 9
  • 27
  • 37
ashokgelal
  • 74,448
  • 25
  • 67
  • 83
  • 10
    cross site duplicate: http://superuser.com/questions/176783/what-is-the-difference-between-executing-a-bash-script-and-sourcing-a-bash-scrip#176788 – lesmana Jul 26 '14 at 19:48
  • 2
    In future you can always try test it with `pwd` on last line. So before script finish then you can check is it working or not.. – sobi3ch Sep 30 '15 at 20:22
  • 5
    @lesmana how is that a duplicate? – aland Jan 08 '16 at 22:43
  • 1
    @aland Because OP does **not** in fact run the script, that's why the working dir doesn't change for him. `cd` command works well inside of scripts, try for yourself. – Alexander Gonchiy Nov 10 '16 at 13:41
  • [Why is cd not a program?](https://unix.stackexchange.com/q/38808/44425), [where is `cd` located?](https://unix.stackexchange.com/q/116955/44425) – phuclv Nov 05 '18 at 15:20
  • `xdotool type --clearmodifiers 'cd ~/projects/java' && xdotool key KP_Enter` – Vyacheslav Konovalov Jul 29 '19 at 13:50
  • Fundamentally this is a duplicate of https://stackoverflow.com/questions/1464253/global-environment-variables-in-a-shell-script – tripleee Mar 22 '21 at 07:08

32 Answers32

658

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"
compie
  • 9,449
  • 15
  • 51
  • 73
Greg Hewgill
  • 828,234
  • 170
  • 1,097
  • 1,237
527

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.

Adam Liss
  • 45,068
  • 11
  • 101
  • 142
  • 97
    `.` is also spelled `source`, choose whichever you find more memorable. – ephemient Nov 01 '08 at 04:41
  • 49
    @Ephemient: Good pointsource That explains why it workssource Also proves that laziness-not necessity-is often the mother of inventionsource – Adam Liss Nov 01 '08 at 18:24
  • 8
    @ephemient: note that source is used in C shell and Bash; it is not supported in POSIX or Korn shells, nor in classic Bourne shell. – Jonathan Leffler Nov 24 '08 at 04:40
  • 2
    "source" is used in Z-shell – Nathan Moos May 14 '13 at 22:52
  • 1
    @AdamLiss It works great, but there is one drawback - somehow source/dot command disables possibility to auto-complete name of the script/command with TAB key. It is still possible to add arguments/input with TAB key, but unfortunately name of the command needs to be input directly. Do you know how to make TAB key work in this case? – Rafal Jan 23 '14 at 08:08
  • @Rafal I tested this on my system (from a PuTTY terminal). I was able to tab complete the name of the command with no problem for both dot and 'source'. Might be your environment? – Stuart Feb 04 '15 at 18:16
  • @Stuart You are right. I just tested this on Ubuntu 14.04 and tab completion works great. It must have been an issue with Ubuntu 13.10 back in January 2014 or maybe my configuration. Thanks for info. – Rafal Feb 19 '15 at 14:33
220

The cd in your script technically worked as it changed the directory of the shell that ran the script, but that was a separate process forked from your interactive shell.

A Posix-compatible way to solve this problem is to define a shell procedure rather than a shell-invoked command script.

jhome () {
  cd /home/tree/projects/java
}

You can just type this in or put it in one of the various shell startup files.

DigitalRoss
  • 135,013
  • 23
  • 230
  • 316
  • 6
    I agree, this is the best answer, bumped. Also, alias may be appropriate in some situations but if he's trying to use cd in a script and wanted to add anything else to it an alias would be useless. – Justin Buser Mar 26 '13 at 05:31
  • 4
    This looks like a solution! And I'm trying to implement it, but it's not performing :( here's my script: #!/bin/bash jhome() { echo "please" cd /home echo "work" } jhome – Gant Laborde Feb 17 '14 at 16:10
  • 1
    @GantMan, you should add this in a"shell startup files", like ~/.bashrc – Jackie Yeh Dec 03 '14 at 02:57
  • If it's in a file you need to use `. filename` or `source filename` so that the current shell sees it, rather than the subshell that ran the command. Or take Jackie's advice and put it in something like `~/.bashrc`. – DigitalRoss Mar 25 '15 at 18:28
  • 4
    You can also use an argument (or two...), ie: `jhome(){ cd /home/tree/projects/$1; }` – irbanana Feb 12 '16 at 17:48
  • 1
    This should be the right way, this makes it possible to use special characters, like "-" for example. – bangkokguy Apr 27 '16 at 17:46
  • 1
    Perfect, just solved my problem flawlessly. This should be marked has the right answer. – Pedro Sousa Jun 06 '16 at 14:12
163

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.)

Boann
  • 44,932
  • 13
  • 106
  • 138
Tzachi.e
  • 1,631
  • 1
  • 10
  • 2
  • 2
    This is cool, and probably good to know. What does the latter do exactly though (how does it work)? This is probably the best solution on this thread. – Jonah Mar 13 '12 at 20:40
  • 2
    fwiw, in the comments section of Adam Liss' answer, ephemient answers the question of what the '.' is. It is the same thing as `source` – g19fanatic Nov 27 '12 at 18:38
  • 1
    Be careful, "source" is a bashism. i.e. dash (Debian default for /bin/sh) does not support it, while "." works as expected. – allo Oct 05 '17 at 09:00
  • 1
    Great answer! also if `myscript.sh` is in a directory included in $PATH, you can source it from anywhere without specifying the full path. – CodeBrew Feb 06 '19 at 22:10
  • This worked for me the best. This solution is the simplest (+1). – HuserB1989 May 05 '20 at 20:56
96

To make a bash script that will cd to a select directory :

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'

  • I created a startup file where I dump all my aliases and custom functions.
  • Then I source this file into my .bashrc to have it set on each boot.

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.

Matt Thomas
  • 1,337
  • 10
  • 3
  • 2
    the file `mastercode.sh` doesn't need the shabang (`#!/bin/sh`), since it is not (and can not be) executed in a subshell. But at the same time, you do need to document the shell "flavor" of this file; e.g., ksh or bash (or (t)csh/zsh,etc), and it's almost certainly not actually `sh`. I usually add a comment (but not the shebang) to communicate this; e.g., _"this file is meant to be sourced (from bash), not run as a shell script."_ – michael Oct 17 '14 at 15:44
  • Another tip (for bash): if you use variables in your script, then as the script is being `source`d (via the `alias`), those variables will leak into your shell environment. To avoid that, do all the work of the script in a function, and just call it at the end of the script. Within the function, declare any variables `local`. – Rhubbarb Apr 17 '15 at 15:55
  • in ubuntu just create ~/.bash_aliases (if it doesn't exist already). Then just add your aliases there, restart the terminal and your done. – Vlad Jun 02 '16 at 07:56
54

You can use . to execute a script in the current shell environment:

. script_name

or alternatively, its more readable but shell specific alias source:

source script_name

This avoids the subshell, and allows any variables or builtins (including cd) to affect the current shell instead.

that other guy
  • 101,688
  • 11
  • 135
  • 166
Sagar
  • 1,243
  • 8
  • 14
39

Jeremy Ruten's idea of using a symlink triggered a thought that hasn't crossed any other answer. Use:

CDPATH=:$HOME/projects

The leading colon is important; it means that if there is a directory 'dir' in the current directory, then 'cd dir' will change to that, rather than hopping off somewhere else. With the value set as shown, you can do:

cd java

and, if there is no sub-directory called java in the current directory, then it will take you directly to $HOME/projects/java - no aliases, no scripts, no dubious execs or dot commands.

My $HOME is /Users/jleffler; my $CDPATH is:

:/Users/jleffler:/Users/jleffler/mail:/Users/jleffler/src:/Users/jleffler/src/perl:/Users/jleffler/src/sqltools:/Users/jleffler/lib:/Users/jleffler/doc:/Users/jleffler/work
Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
35

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 (new) bash prompt in a certain directory after execution of a bash script from within another directory.

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

#!/usr/bin/env bash
cd /home/tree/projects/java
echo -e '\nHit [Ctrl]+[D] to exit this child shell.'
exec bash

To return to the previous, parental bash instance, use Ctrl+D.

Update

At least with newer versions of bash, the exec on the last line is no longer required. Furthermore, the script could be made to work with whatever preferred shell by using the $SHELL environment variable. This then gives:

#!/usr/bin/env bash
cd desired/directory
echo -e '\nHit [Ctrl]+[D] to exit this child shell.'
$SHELL
Serge Stroobandt
  • 19,748
  • 8
  • 84
  • 81
  • 18
    This creates a new subshell. When you type `exit` you will return to the shell where you ran this script. – tripleee Aug 12 '16 at 05:17
  • 1
    When script was called several times seems it creates nested shells and I need to type 'exit' a lot of times. Could this be solved somehow? – VladSavitsky Oct 19 '19 at 08:32
  • 1
    See the other answers: use an alias, use "pushd/popd/dirs", or use "source" – qneill Feb 03 '20 at 23:10
  • @Acumenus You are absolutely right. The `exec` was required with older versions of `bash` and possibly other shells. I updated the answer accordingly. – Serge Stroobandt Oct 25 '20 at 10:50
  • After running `exec bash` can I remain in the script and continue to run another commands? – alper Mar 09 '21 at 13:35
  • @alper Yes, certainly. More commands can be executed in the new child `bash` instance. To return to the previous, parental `bash` instance, use [Ctrl]+[D]. – Serge Stroobandt Mar 11 '21 at 01:10
  • This would work for me if it wasn't for the fact I rely on the shell history to autocomplete commands! Thanks for posting though. – Sridhar Sarnobat Apr 28 '21 at 00:40
25

I got my code to work by using. <your file name>

./<your file name> dose not work because it doesn't change your directory in the terminal it just changes the directory specific to that script.

Here is my program

#!/bin/bash 
echo "Taking you to eclipse's workspace."
cd /Developer/Java/workspace

Here is my terminal

nova:~ Kael$ 
nova:~ Kael$ . workspace.sh
Taking you to eclipe's workspace.
nova:workspace Kael$ 
kaelhop
  • 371
  • 3
  • 5
  • 2
    What's the difference between `. something` and `./something`?? This answer worked for me and I don't understand why. – Dracorat Nov 02 '12 at 20:34
  • `. something` allows you to run the script from any location, `./something` requires you to be in the directory the file is stored in. – Projjol Jul 13 '14 at 13:20
  • 1
    @Dracorat http://stackoverflow.com/questions/13786499/what-is-the-difference-in-a-linux-shell-between-source-and-sh – tripleee Apr 03 '16 at 05:52
  • Can you put the dot in the shebang line? `#!. /bin/bash`? – Sigfried Apr 19 '20 at 18:32
19

simply run:

cd /home/xxx/yyy && command_you_want
warhansen
  • 638
  • 1
  • 6
  • 19
12

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.

Daniel Spiewak
  • 52,267
  • 12
  • 104
  • 120
11

On my particular case i needed too many times to change for the same directory. So on my .bashrc (I use ubuntu) i've added the

1 -

$ nano ~./bashrc

 function switchp
 {
    cd /home/tree/projects/$1
 }

2-

$ source ~/.bashrc

3 -

$ switchp java

Directly it will do: cd /home/tree/projects/java

Hope that helps!

workdreamer
  • 2,698
  • 1
  • 32
  • 37
  • 1
    @W.M. You can eventually do "$ switchp" without any parameter to go directly to the project tree – workdreamer Jul 06 '16 at 09:46
  • 2
    @workdreamer The function approach you described above solved a little trouble here in going into sub-folders which have same parent folder at my system. Thank you. – W.M. Jul 06 '16 at 10:11
11

You can do following:

#!/bin/bash
cd /your/project/directory
# start another shell and replacing the current
exec /bin/bash

EDIT: This could be 'dotted' as well, to prevent creation of subsequent shells.

Example:

. ./previous_script  (with or without the first line)
Thevs
  • 3,105
  • 2
  • 19
  • 31
  • 1
    That gets rather messy after a few runs.. You will have to `exit` (or ctrl+d) several times to exit the shell, for example.. An alias is so much cleaner (even if the shell command outputs a directory, and it cd's to the output - alias something="cd `getnewdirectory.sh`") – dbr Nov 01 '08 at 03:15
  • Note the 'exec'. It makes replace of old shell. – Thevs Nov 01 '08 at 04:06
  • 2
    The exec only replaces the sub-shell that was running the cd command, not the shell that ran the script. Had you dotted the script, then you'd be correct. – Jonathan Leffler Nov 01 '08 at 04:15
  • Make it 'dotted' - no problem. I just proposed solution. It doesn't depend on how you launch this. – Thevs Nov 01 '08 at 04:22
  • 2
    Hehe, I think it's better just to 'dot' one-line script with only cd command :) I'll keep my answer anyway... That will be correct stupid answer to incorrect stupid question :) – Thevs Nov 01 '08 at 05:01
  • http://stackoverflow.com/questions/874452/change-current-directory-from-a-script is what i would propose for interactive usage to launch a dev env. – philippe lhardy Mar 01 '13 at 20:04
  • exec /bin/bash did what I needed. Thanks! – Sergio Abreu May 06 '18 at 13:38
  • This helped me to address a loong pending problem for me. Thanks a lot. – Darshan L Nov 21 '20 at 12:12
7

It only changes the directory for the script itself, while your current directory stays the same.

You might want to use a symbolic link instead. It allows you to make a "shortcut" to a file or directory, so you'd only have to type something like cd my-project.

Paige Ruten
  • 157,734
  • 36
  • 172
  • 191
  • Having that symlink in every directory would be a nuisance. It would be possible to put the symlink in $HOME and then do 'cd ~/my-project'. Frankly, though, it is simpler to use CDPATH. – Jonathan Leffler Nov 01 '08 at 05:56
7

You can combine an alias and a script,

alias proj="cd \`/usr/bin/proj !*\`"

provided that the script echos the destination path. Note that those are backticks surrounding the script name. 

For example, your script could be

#!/bin/bash
echo /home/askgelal/projects/java/$1

The advantage with this technique is that the script could take any number of command line parameters and emit different destinations calculated by possibly complex logic.

knuton
  • 3,177
  • 3
  • 21
  • 22
J. A. Faucett
  • 382
  • 2
  • 6
  • 3
    why? you could just use: `proj() { cd "/home/user/projects/java/$1"; }` => `proj "foo"` (or, `proj "foo bar"` <= in case you have spaces)... or even (for example): `proj() { cd "/home/user/projects/java/$1"; shift; for d; do cd "$d"; done; }` => `proj a b c` => does a `cd` into `/home/user/projects/java/a/b/c` – michael Oct 17 '14 at 15:52
7

You can combine Adam & Greg's alias and dot approaches to make something that can be more dynamic—

alias project=". project"

Now running the project alias will execute the project script in the current shell as opposed to the subshell.

rjmoggach
  • 1,254
  • 13
  • 23
  • This is exactly what I needed to maintain all my script and just call it from bash and maintain current session - this is the PERFECT answer. – Matt The Ninja Sep 18 '19 at 13:55
6

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

Community
  • 1
  • 1
Gene T
  • 5,156
  • 1
  • 22
  • 24
5

In your ~/.bash_profile file. add the next function

move_me() {
    cd ~/path/to/dest
}

Restart terminal and you can type

move_me 

and you will be moved to the destination folder.

mihai.ciorobea
  • 733
  • 5
  • 12
3

You can use the operator && :

cd myDirectory && ls

Jack Bauer
  • 47
  • 1
  • 1
  • Downvote: This does not attempt to answer the actual question here. You can run two commands at the prompt (with `&&` if you want the second to be conditional on the first, or just with `;` or newline between them) but putting this in a script will take you back to "why doesn't the parent shell use the new directory when the `cd` was actually successful?" – tripleee Aug 12 '16 at 05:21
3

While sourcing the script you want to run is one solution, you should be aware that this script then can directly modify the environment of your current shell. Also it is not possible to pass arguments anymore.

Another way to do, is to implement your script as a function in bash.

function cdbm() {
  cd whereever_you_want_to_go
  echo "Arguments to the functions were $1, $2, ..."
}

This technique is used by autojump: http://github.com/joelthelion/autojump/wiki to provide you with learning shell directory bookmarks.

inanutshellus
  • 8,481
  • 9
  • 48
  • 69
thomasd
  • 942
  • 8
  • 14
3

You can create a function like below in your .bash_profile and it will work smoothly.

The following function takes an optional parameter which is a project. For example, you can just run

cdproj

or

cdproj project_name

Here is the function definition.

cdproj(){
    dir=/Users/yourname/projects
    if [ "$1" ]; then
      cd "${dir}/${1}"
    else
      cd "${dir}"
    fi
}

Dont forget to source your .bash_profile

tripleee
  • 139,311
  • 24
  • 207
  • 268
Krish
  • 339
  • 1
  • 4
  • 14
3

This should do what you want. Change to the directory of interest (from within the script), and then spawn a new bash shell.

#!/bin/bash

# saved as mov_dir.sh
cd ~/mt/v3/rt_linux-rt-tools/
bash

If you run this, it will take you to the directory of interest and when you exit it it will bring you back to the original place.

root@intel-corei7-64:~# ./mov_dir.sh

root@intel-corei7-64:~/mt/v3/rt_linux-rt-tools# exit
root@intel-corei7-64:~#

This will even take you to back to your original directory when you exit (CTRL+d)

Developer Guy
  • 2,012
  • 6
  • 17
  • 30
jithu83
  • 459
  • 5
  • 11
2

I did the following:

create a file called case

paste the following in the file:

#!/bin/sh

cd /home/"$1"

save it and then:

chmod +x case

I also created an alias in my .bashrc:

alias disk='cd /home/; . case'

now when I type:

case 12345

essentially I am typing:

cd /home/12345

You can type any folder after 'case':

case 12

case 15

case 17

which is like typing:

cd /home/12

cd /home/15

cd /home/17

respectively

In my case the path is much longer - these guys summed it up with the ~ info earlier.

Acumenus
  • 41,481
  • 14
  • 116
  • 107
chris
  • 29
  • 2
  • 1
    The `cd` in the alias is superfluous and inelegant; the alias should simply ’. ~/case` instead. Also `case` is a reserved keyword, so a rather poor choice for a name. – tripleee Jul 29 '15 at 18:24
1

As explained on the other answers, you have changed the directory, but only within the sub-shell that runs the script. this does not impact the parent shell.

One solution is to use bash functions instead of a bash script (sh); by placing your bash script code into a function. That makes the function available as a command and then, this will be executed without a child process and thus any cd command will impact the caller shell.

Bash functions :

One feature of the bash profile is to store custom functions that can be run in the terminal or in bash scripts the same way you run application/commands this also could be used as a shortcut for long commands.

To make your function efficient system widely you will need to copy your function at the end of several files

/home/user/.bashrc
/home/user/.bash_profile
/root/.bashrc
/root/.bash_profile

You can sudo kwrite /home/user/.bashrc /home/user/.bash_profile /root/.bashrc /root/.bash_profile to edit/create those files quickly

Howto :

Copy your bash script code inside a new function at the end of your bash's profile file and restart your terminal, you can then run cdd or whatever the function you wrote.

Script Example

Making shortcut to cd .. with cdd

cdd() {
  cd ..
}

ls shortcut

ll() {
  ls -l -h
}

ls shortcut

lll() {
  ls -l -h -a
}
intika
  • 5,226
  • 4
  • 26
  • 47
0

If you are using fish as your shell, the best solution is to create a function. As an example, given the original question, you could copy the 4 lines below and paste them into your fish command line:

function proj
   cd /home/tree/projects/java
end
funcsave proj

This will create the function and save it for use later. If your project changes, just repeat the process using the new path.

If you prefer, you can manually add the function file by doing the following:

nano ~/.config/fish/functions/proj.fish

and enter the text:

function proj
   cd /home/tree/projects/java
end

and finally press ctrl+x to exit and y followed by return to save your changes.

(NOTE: the first method of using funcsave creates the proj.fish file for you).

Lane Roathe
  • 420
  • 3
  • 7
0

I have a simple bash script called p to manage directory changing on
github.com/godzilla/bash-stuff
just put the script in your local bin directory (/usr/local/bin)
and put

alias p='. p'

in your .bashrc

godzilla
  • 915
  • 1
  • 9
  • 18
  • what does this do? it looks like it would recursively run itself, although I'm sure if you've run it before it doesn't ;) – Ryan Taylor Mar 15 '19 at 18:03
0

You need no script, only set the correct option and create an environment variable.

shopt -s cdable_vars

in your ~/.bashrc allows to cd to the content of environment variables.

Create such an environment variable:

export myjava="/home/tree/projects/java"

and you can use:

cd myjava

Other alternatives.

Community
  • 1
  • 1
Gauthier
  • 34,041
  • 11
  • 53
  • 87
0

Note the discussion How do I set the working directory of the parent process?

It contains some hackish answers, e.g. https://stackoverflow.com/a/2375174/755804 (changing the parent process directory via gdb, don't do this) and https://stackoverflow.com/a/51985735/755804 (the command tailcd that injects cd dirname to the input stream of the parent process; well, ideally it should be a part of bash rather than a hack)

18446744073709551615
  • 14,600
  • 3
  • 82
  • 116
0

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.

Yuri Nudelman
  • 2,177
  • 2
  • 11
  • 18
0

I have to work in tcsh, and I know this is not an elegant solution, but for example, if I had to change folders to a path where one word is different, the whole thing can be done in the alias

a alias_name 'set a = `pwd`; set b = `echo $a | replace "Trees" "Tests"` ; cd $b'

If the path is always fixed, the just

a alias_name2 'cd path/you/always/need'

should work In the line above, the new folder path is set

ZakS
  • 779
  • 10
  • 24
0

This combines the answer by Serge with an unrelated answer by David. It changes the directory, and then instead of forcing a bash shell, it launches the user's default shell. It however requires both getent and /etc/passwd to detect the default shell.

#!/usr/bin/env bash
cd desired/directory
USER_SHELL=$(getent passwd <USER> | cut -d : -f 7)
$USER_SHELL

Of course this still has the same deficiency of creating a nested shell.

Acumenus
  • 41,481
  • 14
  • 116
  • 107
-3

You can execute some lines in the same subshell if you end lines with backslash.

cd somedir; \
pwd
Max
  • 3
  • 1