git 如何在 Shell 脚本中更改目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14776006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 08:09:05  来源:igfitidea点击:

How to change directory in a Shell Script?

gitshell

提问by Ron van der Heijden

This is my first time I create a Shell Script.

这是我第一次创建 Shell 脚本。

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

目前我正在使用 nodejs,我正在尝试创建一个 Shell 脚本并在其中使用 git。

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).

这个脚本位于我的桌面上并且它可以工作(是的,我已经安装了 git)。

What I want

我想要的是

After it downloaded the git repository, I want to:

下载 git 存储库后,我想:

cd /site
npm install

I have Nodejs and NPM installed.

我安装了 Nodejs 和 NPM。

What I tried

我试过的

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

我只想进入创建的文件夹并运行命令,npm install所以我想这样做:

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

Also I've read about the aliasand 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?

谁能帮助我?

回答by miku

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):

它可能比您想象的更简单(因为您一直在编写 bash(或您使用的任何 shell)“脚本”,只需使用命令行即​​可):

#!/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 npmif cd sitesucceeds (more on that in Chaining commands together):

为了让它更健壮一点,只有npmcd site成功时才运行(更多关于链接命令中的内容):

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:

仅仅因为我读了一些关于可靠 bash 的文章,这里还有另一个版本:

#!/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