dbe*_*uer 2 command-line scripts
我需要使用来自生成文件的相对路径运行应用程序 (msp430-gcc)。问题是该应用程序位于不同的文件夹分支中,因此我需要执行以下操作:
../../../../tools/msp430/bin/msp430-gcc
Run Code Online (Sandbox Code Playgroud)
这里的问题是系统无法找到应用程序。但是,如果我这样做:
cd ../../../../tools/msp430/bin
./msp430-gcc
Run Code Online (Sandbox Code Playgroud)
那么它的工作原理。
您知道如何在不使用“cd”的情况下从初始位置运行应用程序吗?
在此先感谢您的时间。
这里的关键词是:在不同的工作目录下运行命令。您可以自行 google 以查找更多信息。
您可以使用括号调用它 - ()
$ (cd ../../../../tools/msp430/bin &&./msp430-gcc)
Run Code Online (Sandbox Code Playgroud)
括号将创建一个新的子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.
Run Code Online (Sandbox Code Playgroud)
其中 alist
只是一个正常的命令序列。
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.
Run Code Online (Sandbox Code Playgroud)
总之: subshell 将看到来自 的所有变量parent shell
,但它会将它们用作local。子shell对变量所做的更改不影响parent shell
另一种方法使用sh
:
$ sh -c 'cd ../../../../tools/msp430/bin; ./msp430-gcc'
Run Code Online (Sandbox Code Playgroud)
在这种情况下sh -c
不会产生subshell,而是创建自己的新 shell。这就是为什么它看不到parent shell
variables。所以请记住:如果你在执行sh -c
新 shell之前设置了一些变量将看不到它。
但也有使用之间有点混淆单引号 ''
和双引号 ""
在sh -c
。看到这个问题来理解差异,我只会展示小例子:
$ TEST=test1
$ sh -c 'echo $TEST'
$ sh -c 'TEST=test2;echo $TEST'
test2
Run Code Online (Sandbox Code Playgroud)
执行第一个命令后,什么都没有打印出来。这是因为新外壳没有TEST
变量,''
也没有扩展$TEST
。
$ sh -c "echo $TEST"
test1
$ sh -c "TEST=test2;echo $TEST"
test1
Run Code Online (Sandbox Code Playgroud)
这里第一个命令$TEST
因为 using 被扩展""
,即使我们TEST
在新 shell 中设置变量$TEST
已经扩展,它打印出test1
sh -c "command"
. 非常完整的答案。''
和之间的区别""