sh 可执行 if else 语句

sh executable if else statement

如果可执行文件输出特定字符串,我如何使用 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"

编辑

尝试

#!/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 ))"

orig

你非常接近。为什么不使用不受欢迎的 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