内联 if shell 脚本
是否可以像这样在命令行中执行 shell 脚本:
counter=`ps -ef | grep -c "myApplication"`; if [ $counter -eq 1 ] then; echo "true";
>
上面的示例不起作用,我只得到 >
字符,而不是我想要得到的结果,即“true”
当我执行 <代码>ps -ef | grep -c "myApplication 我得到 1 个输出。是否可以从脚本中的单行创建结果?谢谢
Is it possible to execute shell script in command line like this :
counter=`ps -ef | grep -c "myApplication"`; if [ $counter -eq 1 ] then; echo "true";
>
Above example is not working I get only >
character not the result I'm trying to get, that is "true"
When I execute ps -ef | grep -c "myApplication
I get 1 output. Is it possible to create result from single line in a script ? thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它不起作用,因为您错过了
fi
来结束if
语句。您可以使用以下方法进一步缩短它:
另外,请注意 ps -ef | 的问题。 grep ... 匹配 @DigitalRoss 的回答。
更新
事实上,您可以使用
pgrep
做得更好:It doesn't work because you missed out
fi
to end yourif
statement.You can shorten it further using:
Also, do take note the issue of
ps -ef | grep ...
matching itself as mentioned in @DigitalRoss' answer.update
In fact, you can do one better by using
pgrep
:其他响应已经解决了您的语法错误,但我强烈建议您将该行更改为:
如果您不尝试将出现次数限制为正好 1(例如,如果您只是尝试检查输出行 myApplication 并且您期望它永远不会出现多次)然后只需执行以下操作:(
如果您需要设置变量计数器以供以后处理,那么这些解决方案都不合适。
)和 ||运算符通常比嵌入 if/then 结构更清晰,尤其是在单行语句中。
Other responses have addressed your syntax error, but I would strongly suggest you change the line to:
If you are not trying to limit the number of occurrences to exactly 1 (eg, if you are merely trying to check for the output line myApplication and you expect it never to appear more than once) then just do:
(If you need the variable counter set for later processing, neither of these solutions will be appropriate.)
Using short circuited && and || operators is often much clearer than embedding if/then constructs, especially in one-liners.
是的,修复了语法问题
几乎可以工作。正确的语法是:
但请注意,在涉及
ps
和grep
的此类表达式中,grep
通常会匹配自身,因为字符 " grep -c Myapplication”出现在 ps 列表中。有几种方法可以解决这个问题,其中之一是 grep 查找类似[M]yapplication
的内容。Yes, with syntax issues fixed
That almost worked. The correct syntax is:
But note that in an expression of this sort involving
ps
andgrep
, thegrep
will usually match itself because the characters "grep -c Myapplication" show up in the ps listing. There are several ways around that, one of them is to grep for something like[M]yapplication
.我正在使用 Mac OS,并且以下工作非常好
true
之后 [ 和之前 ] 需要空间
I am using Mac OS and following worked very well
true
Space is needed after [ and before ]
我正在努力将多行输入合并到命令中并将其结果放入变量(而不是文件)中,并提出这个解决方案:
请注意,单引号单词已被替换,因为否则我会收到它对双引号的自动替换... ksh、HP-UX。
希望这对其他人也有帮助。
I was struggling to combine both multiple lines feed into command and getting its results into a variable (not a file) and come up with this solution:
Please note that single-quotes word was substituted, because otherwise I was receiving its autosubstitution to double quotes... ksh, HP-UX.
Hopefully this will be helpful for somebody else too.