如何在 shell 脚本中检查命令的输出是否包含特定的单词?

如何在 shell 脚本中检查命令的输出是否包含特定的单词?

有时我会遇到网络连接问题,需要重新运行上一个命令。但不确定如何使用 if else 语句?

for var in ./*
do python2.7 submit.py $var
//check if output of previous do statement has word traceback
 if    
   python2.7 submit.py $var
 else
   //if it does not contain word traceback continue with the for loop
   continue??
done

答案1

假设您不需要程序输出用于其他任何用途,我会这样做:

for var in ./*
do
  while ! python2.7 submit.py "$var" | grep -qFe traceback
  do
    echo "Trying again for $var ..."
  done
  echo "Succeeded for $var."
done

如果程序输出很小,最好将其重定向到变量并检查(因为它每次迭代节省一个 fork+exec):

for var in ./*
do
  while [[ "$(python2.7 submit.py "$var")" != *traceback* ]]
  do
    echo "Trying again for $var ..."
  done
  echo "Succeeded for $var."
done

相关内容