[英]How to get output from shell script on mac?
I am looking to run a command in shell script and check its output.If it has certain text, I want to set a global variable to particular string.Below is what I have done so far. 我想在shell脚本中运行命令并检查其输出。如果它具有某些文本,我想将全局变量设置为特定的字符串。以下是我到目前为止所做的事情。 The command
~/Library/Android/sdk/tools/android list | grep 'The "android" command is deprecated.
命令
~/Library/Android/sdk/tools/android list | grep 'The "android" command is deprecated.
~/Library/Android/sdk/tools/android list | grep 'The "android" command is deprecated.
works in terminal however it doesn't seem to work in shell script. 在终端中工作,但是在shell脚本中似乎不工作。 What am I missing here?
我在这里想念什么?
#!/bin/bash
Android_Command=''
MKCOMMAND='~/Library/Android/sdk/tools/android list | grep 'The "android" command is deprecated.''
RESP=$($MKCOMMAND)
echo $RESP
if [ '$RESP'=='The "android" command is deprecated.' ]; then
Android_Command='Version2'
else
Android_Command='Version1'
fi
Following is the output that I get 以下是我得到的输出
~/Library/Android/sdk/tools/android: No such file or directory
From your last edit, it has become clear that you were not executing the script from your terminal but rather you were just executing a single line from it. 从上一次编辑可以清楚地看到,您不是从终端执行脚本,而是从其中执行一行。
In shell scripts, anything inside a single quote is not subject to shell expansion. 在shell脚本中,单引号内的所有内容都不受shell扩展的约束。 Having said that, both
~
and |
话虽如此,
~
和|
cannot be quoted. 无法引用。
Redirections are created by the shell before execution. 重定向是在执行前由Shell创建的。 This means
MKCOMMAND
cannot be executed because the pipe |
这意味着无法执行
MKCOMMAND
因为管道|
will be treated as a parameter to the command android
. 将被视为
android
命令的参数。
So how do we deal with this kind of script? 那么我们如何处理这种脚本呢? Don't quote any redirections.
不要引用任何重定向。
#!/bin/bash
if ~/Library/Android/sdk/tools/android list | grep -q 'The "android" command is deprecated.'; then
Android_Command='Version2'
else
Android_Command='Version1'
fi
The if
statement accepts a complex statement. if
语句接受一个复杂的语句。 grep -q
will return zero if it finds the string and non-zero otherwise. 如果找到字符串,则
grep -q
将返回零,否则返回非零。
Try running your command directly instead (without using the MKCOMMAND
variable): 请尝试直接运行命令(而不使用
MKCOMMAND
变量):
RESP=$(~/Library/Android/sdk/tools/android list | grep 'The "android" command is deprecated.')
echo $RESP
...
This (quick!) hack might bypass some Bash quoting issues you may be having. 这种(快速!)黑客可能会绕过您可能遇到的一些Bash 报价问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.