使用Linux shell,如何使用与当前工作目录不同的工作目录启动程序?
例如,我有一个二进制文件helloworld
,它在current directory中创建了文件hello-world.txt
.
目前,我在/b
号目录中.我想启动运行../a/helloworld
的程序,把hello-world.txt
放在第三个目录/c
的某个地方.
使用Linux shell,如何使用与当前工作目录不同的工作目录启动程序?
例如,我有一个二进制文件helloworld
,它在current directory中创建了文件hello-world.txt
.
目前,我在/b
号目录中.我想启动运行../a/helloworld
的程序,把hello-world.txt
放在第三个目录/c
的某个地方.
按如下方式调用该程序:
(cd /c; /a/helloworld)
括号将生成一个子壳.然后,这个子shell将其工作目录更改为/c
,然后从/a
执行helloworld
.程序退出后,子shell终止,并返回父shell的提示符,该提示符位于启动的目录中.
Error handling:为避免在未更改目录的情况下运行程序,例如拼写错误/c
时,使helloworld
的执行有条件:
(cd /c && /a/helloworld)
Reducing memory usage:为了避免hello world执行时子shell浪费内存,请通过exec调用helloworld
:
(cd /c && exec /a/helloworld)
[感谢Josh and Juliano提供了改进此答案的提示!]