Glam Prestige Journal

Bright entertainment trends with youth appeal.

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

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

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!

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy