使用 Linux shell,如何使用与当前工作目录不同的工作目录启动程序?
例如,我有一个二进制文件 helloworld
,它在 当前目录 中创建文件 hello-world.txt
。
该文件位于目录 /a
内。
目前,我在目录 /b
中。我想启动我的程序运行 ../a/helloworld
并在第三个目录 /c
的某处获取 hello-world.txt
。
最佳答案
这样调用程序:
(cd /c; /a/helloworld)
括号会产生一个子shell。然后,这个子 shell 将其工作目录更改为 /c
,然后从 /a
执行 helloworld
。程序退出后,子 shell 终止,将您返回到父 shell 的提示符,在您开始的目录中。
错误处理: 避免在未更改目录的情况下运行程序,例如当 /c
拼写错误时,使 helloworld
的执行有条件:
(cd /c && /a/helloworld)
减少内存使用:为避免在 hello world 执行时让 subshell 浪费内存,请通过 exec 调用 helloworld
:
(cd /c && exec /a/helloworld)
[感谢 Josh and Juliano提供改进此答案的提示!]
https://stackoverflow.com/questions/786376/