如何从 Linux shell 运行与当前工作目录不同的程序? [英] How do I run a program with a different working directory from current, from Linux shell?

查看:34
本文介绍了如何从 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 并在第三个目录 /c 中的某个位置获取 hello-world.txt.

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)

括号会产生一个子shell.这个子shell然后将其工作目录更改为/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)

减少内存使用:为了避免子shell在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)

[感谢 Josh 和 Juliano 提供有关改进此答案的提示!]

[Thanks to Josh and Juliano for giving tips on improving this answer!]

这篇关于如何从 Linux shell 运行与当前工作目录不同的程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆