临时更改 bash 中的当前工作目录以运行命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10382141/
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-09 22:00:09  来源:igfitidea点击:

Temporarily change current working directory in bash to run a command

bashshellterminalworking-directory

提问by Ethan Zhang

I know I can use cdcommand to change my working directory in bash.

我知道我可以使用cd命令在 bash 中更改我的工作目录。

But if I do this command:

但是如果我执行这个命令:

cd SOME_PATH && run_some_command

Then the working directory will be changed permanently. Is there some way to change the working directory just temporarily like this?

然后工作目录将被永久更改。有没有办法像这样临时更改工作目录?

PWD=SOME_PATH run_some_command

回答by codaddict

You can run the cdand the executable in a subshell by enclosing the command line in a pair of parentheses:

cd通过将命令行括在一对括号中,您可以在子 shell 中运行和 可执行文件:

(cd SOME_PATH && exec_some_command)

Demo:

演示:

$ pwd
/home/abhijit
$ (cd /tmp && pwd)  # directory changed in the subshell
/tmp 
$ pwd               # parent shell's pwd is still the same
/home/abhijit

回答by pizza

bash has a builtin

bash 有一个内置

pushd SOME_PATH
run_stuff
...
...
popd 

回答by yazu

Something like this should work:

这样的事情应该工作:

sh -c 'cd /tmp && exec pwd'