我想调试由随机过程运行的代码的某些情况。
所以我将printf放在我要调试的部分的代码中。
在得到printf语句之前,有什么方法可以在终端上运行此代码?
我想像运行shell程序
while true;
if [ "$(./mycode || grep "statement")"];
then break;
done;
(它不是可运行的,我只是想告诉您语义。)
但是我想if语句中的每个返回值都为true。
我想调试由随机过程运行的代码的某些情况。
所以我将printf放在我要调试的部分的代码中。
在得到printf语句之前,有什么方法可以在终端上运行此代码?
我想像运行shell程序
while true;
if [ "$(./mycode || grep "statement")"];
then break;
done;
(它不是可运行的,我只是想告诉您语义。)
但是我想if语句中的每个返回值都为true。
If you want to quit as soon as you see the line in question it's best to avoid
grep
. It may have an internal buffer and try to read past the matching line. The same goes forsed
, and most other programs in fact.I would use an explicit
while read
loop.read
never reads more than one line so it won't overshoot.语法可能看起来很奇怪,将输出传递到一个循环中。之所以有效,是因为循环实际上只是一个大的复合命令。确实,这是一个巧妙的技巧。
如果要使其更具可读性,可以将循环重构为一个函数。
笔记:
#!/bin/bash
shebang line to use them.IFS= read -r
is standard boilerplate to make theread
call safer.IFS=
prevents it from stripping leading whitespace, and-r
tells it to leave backslashes alone. For historical reasons these are opt-out features not opt-in.