Search code examples
bashenvironment

Change the current directory from a Bash script


Is it possible to change current directory from a script?

I want to create a utility for directory navigation in Bash. I have created a test script that looks like the following:

#!/bin/bash
cd /home/artemb

When I execute the script from the Bash shell the current directory doesn't change. Is it possible at all to change the current shell directory from a script?


Solution

  • You need to convert your script to a shell function:

    #!/bin/bash
    #
    # this script should not be run directly,
    # instead you need to source it from your .bashrc,
    # by adding this line:
    #   . ~/bin/myprog.sh
    #
    
    function myprog() {
      A=$1
      B=$2
      echo "aaa ${A} bbb ${B} ccc"
      cd /proc
    }
    

    The reason is that each process has its own current directory, and when you execute a program from the shell it is run in a new process. The standard "cd", "pushd" and "popd" are builtin to the shell interpreter so that they affect the shell process.

    By making your program a shell function, you are adding your own in-process command and then any directory change gets reflected in the shell process.