1

When I change working directory in a script and execute it, the working directory only changes to specified path while in the script. Here is my script:
#!/bin/bash
cd /media/hard/drive/partitionX/
pwd
(this was to make sure if it actually changed directory)

When I execute it, it returns the specified path, but my working directory in terminal doesn't change. How do I change the working directory in my terminal through a script?

1

2 Answers 2

6

This is normal. The "current" or "working" directory is a per-process parameter, and a process can only change its own working directory. Standalone scripts are executed as a separate shell process and cannot affect the parent shell (in fact, the parent might not always be a shell).

You will need to use features internal to your shell, such as:

  • shell functions:

    mycd() {
        cd /media/hard/drive/partitionX/;
        pwd;
    }
    
  • shell aliases:

    alias mycd='cd /media/hard/drive/partitionX; pwd'
    
  • "source" a script instead of executing it:

    . mycd.sh
    

If your main goal is to create shortcuts to certain directories, you can also use:

  • symlinks in a more convenient location:

    ln -s /media/hard/drive/partitionX ~/partX
    cd ~/partX
    
  • variables ($mydir):

    mydir=/media/hard/drive
    cd $mydir
    
  • the $CDPATH feature:

    CDPATH=".:/media/hard/drive"
    cd partitionX
    
1
  • Wow, thanks a lot! This was extremely helpful! Thanks for the detailed answer with all the possibilities! Commented Dec 1, 2018 at 13:15
1

Actually, I just found, after many searches, that if you need to change the directory, and still keep the same shell, so you will get all the answers in your currect script, you can use:

(cd your_dir; do_some_command_there)

For example, what I needed to use, was:

((cd your_dir; git remote -v | wc -l)

Works like a charm!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .