bashshellworking-directory

How can Bash execute a command in a different directory context?


I have a common command that gets called from within very specific directories. There is only one executable sitting in /bin for this program, and the current working directory is very important for running it correctly. The script affects the files that live inside the directory it is run within.

Now, I also have a custom shell script that does some things in one directory, but I need to call that command mentioned above as if it was in another directory.

How do you do this in a shell script?


Solution

  • You can use the cd builtin, or the pushd and popd builtins for this purpose. For example:

    # do something with /etc as the working directory
    cd /etc
    :
    
    # do something with /tmp as the working directory
    cd /tmp
    :
    

    You use the builtins just like any other command, and can change directory context as many times as you like in a script.