sh可执行if else语句

时间:2016-11-14 18:25:47

标签: if-statement sh counter executable

如果可执行文件输出某个字符串,如何使用sh脚本进行测试?我使用./program运行可执行文件,并将其打印到控制台hellogoodbye。我想运行1000次并计算每个输出出现的次数。

#!/bin/sh
count=0
secs=60                        # Set interval (duration) in seconds.
endTime=$(( $(date +%s) + secs )) # Calculate end time.

while [ $(date +%s) -lt $endTime ]; do  # Loop until interval has elapsed.
    if [[ ./program = *hello* ]]; then
        count++
    fi
done

编辑(根据给出的答案部分修复):

#!/bin/sh


winCount=0
totalCount=0
secs=60                        # Set interval (duration) in seconds.
endTime=$(( $(date +%s) + secs )) # Calculate end time.

while [ $(date +%s) -lt $endTime ]; do  # Loop until interval has elapsed.
        totalCount++
        case $(./program) in
                *\[1\]\ \[1\]\ \[1\]* )((winCount++)) ;;
        esac
done
echo "wins=$winCount"
echo "total=$totalCount"

1 个答案:

答案 0 :(得分:1)

修改

尝试

#!/bin/bash
runCount=0
secs=60                        # Set interval (duration) in seconds.
endTime=$(( $(date +%s) + secs )) # Calculate end time.

while [ $(date +%s) -lt $endTime ]; do  # Loop until interval has elapsed.
  # bash/ksh only ((runCount++))
  runCount=$(expr $runCount + 1 )
  case $(./program) in
      *\[1\]\ \[1\] ) ((matchCnt++)) ;;
  esac
done
echo "avg=$(( runCount / matchCnt ))"

<强>原稿

你非常接近。为什么不使用未经认可的case语句,即。

#!/bin/sh
count=0
secs=60                        # Set interval (duration) in seconds.
endTime=$(( $(date +%s) + secs )) # Calculate end time.

while [ $(date +%s) -lt $endTime ]; do  # Loop until interval has elapsed.
  case $(./program) in
      *hello* )((helloCnt++)) ;;
      *goodbye* ) ((goodbyeCnt++)) ;;
  esac
done
echo "hellos=$helloCnt    goodByes=$goodbyCnt"

我想不出./program的简单替代品,所以我无法测试它。

如果您收到错误消息,请与我们联系。

此外,如果你的目标是尽可能快地运行它,那么使用循环计数器将消除对$(date +%s)驱动循环的相对昂贵的调用。即。

 for (i=0;i<1000;i++) ; do
     case $(./program) in
         ...
     esac
 done

IHTH