linux - 内联 if shell 脚本

是否可以像这样在命令行中执行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

https://stackoverflow.com/questions/4986109/

相关文章:

linux - 如何将上下文后的 grep 设置为 "until the next blank li

c++ - 将字符串作为指针或文字传递时,strcmp() 返回值不一致

Linux 上的 C++ 开发 - 我从哪里开始?

linux - 将 Emacs 复制/粘贴与系统复制/粘贴集成

c - 分段故障处理

linux - 如何在 Bash 字符串中添加新行?

c - 使用 gdb 将地址转换为行

c - 无论如何要从命令行获取c程序的返回值?

c - 如何在 Linux 中创建高分辨率计时器来测量程序性能?

linux - find 和 ls 上的通配符