使用相对(上部)路径执行命令。 使用另一个工作目录

我需要使用makefile中的相对路径运行应用程序(msp430-gcc)。 问题是应用程序位于不同的文件夹分支中,因此我需要执行以下操作:

../../../../tools/msp430/bin/msp430-gcc 

这里的问题是系统无法找到应用程序。 但是,如果我这样做:

 cd ../../../../tools/msp430/bin ./msp430-gcc 

然后它工作。

你知道如何在不使用“cd”的情况下从我的初始位置运行应用程序吗?

在此先感谢您的时间。

这里的关键字是: 带有不同工作目录的running命令 。 您可以自己谷歌查找更多信息。

你可以用圆括号来调用它 – ()

 $ (cd ../../../../tools/msp430/bin &&./msp430-gcc) 

括号将创建一个新的子shell来执行其中的命令。 这个新的子shell将更改此目录中的目录和执行程序。

man bash引用

 (list) list is executed in a subshell environment (see COMMAND EXECUTION ENVIRONMENT below). Variable assignments and builtin commands that affect the shell's environment do not remain in effect after the command completes. The return status is the exit status of list. 

其中list只是一个正常的命令序列。

 Variables in a subshell are not visible outside the block of code in the subshell. They are not accessible to the parent process, to the shell that launched the subshell. These are, in effect, local variables. Directory changes made in a subshell do not carry over to the parent shell. 

总之:subshel​​l将从parent shell看到所有变量,但它会将它们用作本地变量。 子shell对变量所做的更改不会影响parent shell


使用sh另一种方法:

 $ sh -c 'cd ../../../../tools/msp430/bin; ./msp430-gcc' 

在这种情况下, sh -c不会生成子shell ,而是创建自己的新shell。 这就是它无法看到parent shell 变量的原因 。 所以请记住:如果在执行sh -c之前设置了一些变量,那么新的shell将无法看到它。

但是在sh -c使用单引号 ''双引号 ''之间也有一点混淆。 看到这个问题来理解差异,我只会举一些例子:

 $ TEST=test1 $ sh -c 'echo $TEST' $ sh -c 'TEST=test2;echo $TEST' test2 

执行第一个命令后,没有打印出来。 这是因为新shell没有TEST变量,并且''不扩展$TEST

 $ sh -c "echo $TEST" test1 $ sh -c "TEST=test2;echo $TEST" test1 

这里第一个命令$TEST因为使用""而被扩展,即使我们在新shell中设置了TEST变量$TEST已经扩展了,它打印出test1


来源

  1. 关于sh -c "command" 。 非常完整的答案。
  2. 关于括号
  3. 类似的问题
  4. 关于括号的 bash指南
  5. ''""之间'' 区别