linux - 内联 if shell 脚本

标签 linux shell scripting sh

是否可以像这样在命令行中执行shell脚本:

counter=`ps -ef | grep -c "myApplication"`; if [ $counter -eq 1 ] then; echo "true";
>

上面的例子不起作用我只得到 > 字符而不是我想要得到的结果,即“真”

当我执行 ps -ef | grep -c "myApplication 我得到 1 个输出。是否可以从脚本中的单行创建结果?谢谢

最佳答案

它不起作用,因为您错过了 fi 来结束您的 if 语句。

counter=`ps -ef | grep -c "myApplication"`; if [ $counter -eq 1 ]; then echo "true"; fi

您可以使用以下方法进一步缩短它:

if [ $(ps -ef | grep -c "myApplication") -eq 1 ]; then echo "true"; fi

另外,请注意 ps -ef | 的问题。 grep ... 匹配自身,如 @DigitalRoss' answer 中所述.

更新

事实上,你可以使用 pgrep 做得更好:

if [ $(pgrep -c "myApplication") -eq 1 ]; then echo "true"; fi

关于linux - 内联 if shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4986109/

相关文章:

windows - 用于从文件中的名称列表创建文件夹的 Powershell 脚本

c - 如何让变量名和行号出现在 GDB 中?

c++ - 为什么在链接时不解析共享库的符号?

c - 暂停破坏 shell

iphone - iPhone 上的 Python

python - 将通配符参数从 bash 传递到 python

带有通配符和隐藏文件的 Bash for 循环

android - 阐明重载图形术语

linux - 检测后台操作

linux - watch命令错误放置终端内容报错