Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change directory in a Shell Script?

Tags:

git

shell

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?

like image 629
Ron van der Heijden Avatar asked Dec 12 '25 05:12

Ron van der Heijden


1 Answers

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
like image 140
miku Avatar answered Dec 15 '25 12:12

miku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!