How to change directory in a Shell Script?

15,161

It might be simpler than you think (since you are writing bash (or whatever shell you use) 'scripts' all time, just by using the command line):

#!/bin/bash
git clone git://github.com/Tmeister/Nodejs---Boilerplate.git site
cd site
npm install

cd - # back to the previous directory

To make it a bit more robust, only run npm if cd site succeeds (more on that in Chaining commands together):

git clone git://github.com/Tmeister/Nodejs---Boilerplate.git site
cd site && npm install && cd -

Just because I read some article about reliable bash, here's yet another version:

#!/bin/bash

OLDPWD=$(pwd)
git clone git://github.com/Tmeister/Nodejs---Boilerplate.git site \
    && cd site && npm install && cd "$OLDPWD"
function atexit() { cd "$OLDPWD"; }
trap atexit EXIT # go back to where we came from, however we exit
Share:
15,161
Ron van der Heijden
Author by

Ron van der Heijden

A software engineer that loves Code, Coffee, and Cats

Updated on June 04, 2022

Comments

  • Ron van der Heijden
    Ron van der Heijden almost 2 years

    This is my first time I create a Shell Script.

    At the moment I'm working with nodejs and I am trying to create a Shell Script and use git in it.

    What my script looks like

    #!/bin/bash
    git clone git://github.com/Tmeister/Nodejs---Boilerplate.git site
    

    This script is located at my desktop and it works (yes I have git installed).

    What I want

    After it downloaded the git repository, I want to:

    cd /site
    npm install
    

    I have Nodejs and NPM installed.

    What I tried

    I just want to dive into the created folder and run the command npm install so I thought to do this:

    #!/bin/bash
    git clone git://github.com/Tmeister/Nodejs---Boilerplate.git site
    echo "cd /site"
    echo "npm install"
    

    Also I've read about the alias and I tried

    #!/bin/bash
    git clone git://github.com/Tmeister/Nodejs---Boilerplate.git site
    alias proj="cd /site"
    proj
    echo "npm install"
    

    But nothing works..

    Anyone who can help me?

  • Jens
    Jens about 10 years
    What is the point of cd'ing just before exit? What could be different if the script didn't?