如何从Linux Shell运行与当前工作目录不同的程序?
使用 Linux shell ,如何使用与当前工作目录不同的工作目录启动程序?
Using a Linux shell, how do I start a program with a different working directory from the current working directory?
例如,我有一个二进制文件helloworld
,可在当前目录中创建文件hello-world.txt
.
此文件位于目录/a
中.
For example, I have a binary file helloworld
that creates the file hello-world.txt
in the current directory.
This file is inside of directory /a
.
当前,我在目录/b
中.我想启动运行../a/helloworld
的程序,并将hello-world.txt
放在第三个目录/c
中.
Currently, I am in the directory /b
. I want to start my program running ../a/helloworld
and get the hello-world.txt
somewhere in a third directory /c
.
像这样调用程序:
(cd /c; /a/helloworld)
括号引起子壳的产生.然后,该子外壳将其工作目录更改为/c
,然后从/a
执行helloworld
.程序退出后,子Shell终止,返回到您从其开始的目录中的父Shell提示符.
The parentheses cause a sub-shell to be spawned. This sub-shell then changes its working directory to /c
, then executes helloworld
from /a
. After the program exits, the sub-shell terminates, returning you to your prompt of the parent shell, in the directory you started from.
错误处理::为避免在未更改目录的情况下运行程序,例如/c
拼写错误时,请按条件执行helloworld
:
Error handling: To avoid running the program without having changed the directory, e.g. when having misspelled /c
, make the execution of helloworld
conditional:
(cd /c && /a/helloworld)
减少内存使用量:为避免在hello world执行时子外壳浪费内存,请通过exec调用helloworld
:
Reducing memory usage: To avoid having the subshell waste memory while hello world executes, call helloworld
via exec:
(cd /c && exec /a/helloworld)
[Thanks to Josh and Juliano for giving tips on improving this answer!]