检查脚本中的字符串和文件是否为空 shell

Check string and file empty in script shell

我有下面的脚本查询由 HTTP 查询生成的字符串 ERROR,我希望它检查所有行,只检查 return me TRUE 当出现错误或文件为空时

result.log

Collecting: LINK1 HTTP 200
EXCEPT ERROR - REST API LINK2 returned HTTP Error

脚本:

  1 cat /healthcheck/bin/gaps/result.log | grep HTTP | while read line
  2 do
  3     echo "$line" | grep "ERROR" >/dev/null
  4     if [ $? = 0 ]; then
  5         RESULT = "TRUE"
  6     fi
  7 done
  8
  9 echo $RESULT

输出:

./check.sh: line 5: RESULT: command not found
./check.sh: line 5: RESULT: command not found

Shell 检查:

$ shellcheck myscript

Line 1:
cat /healthcheck/bin/gaps/result.log | grep HTTP | while read line
^-- SC2148: Tips depend on target shell and yours is unknown. Add a shebang or a 'shell' directive.
    ^-- SC2002: Useless cat. Consider 'cmd < file | ..' or 'cmd file | ..' instead.
                                                         ^-- SC2162: read without -r will mangle backslashes.

Line 4:
     if [ $? = 0 ]; then
          ^-- SC2181: Check exit code directly with e.g. 'if mycmd;', not indirectly with $?.

Line 5:
         RESULT = "TRUE"
         ^-- SC2030: Modification of RESULT is local (to subshell caused by pipeline).
                ^-- SC1068: Don't put spaces around the = in assignments (or quote to make it literal).

Line 9:
echo $RESULT
     ^-- SC2031: RESULT was modified in a subshell. That change might be lost.

$ 

管道在子shell中运行。子 shell 的更改对父 shell 不可见。站点 bashfaq/024 提供了可能的解决方法。

如果|是行的最后一个字符,你可以换行,不需要为管道构建超长行。

大写变量按照惯例保留用于导出变量。

cat ... | grepcat. 的无用用法 只是 grep ...< file grep.

当您检查命令 return 值时,只是 if the command; then 而不是 the command; if [ $? ...

if 中使用 greps 退出状态。在 bash 中只是 if <<<"$string" grep -q "pattern"; then。在 posix shell 中执行 if printf "%s\n" "$string" | grep -q "pattern"; then.

Bash space 知道。 RESULT = "TRUE" 使用两个参数执行名为 RESULT 的命令。这是 RESULT="TRUE"

使用while IFS= read -r line来准确读出整行。

所以虽然你可以:

cat /healthcheck/bin/gaps/result.log |
grep HTTP |
{
  while read line
  do
      echo "$line" | grep "ERROR" >/dev/null
      if [ $? -eq 0 ]; then
         RESULT="TRUE"
      fi
  done
  echo $RESULT
}

在你的情况下,它只是:

if grep "HTTP" /healthcheck/bin/gaps/result.log | grep -q "ERROR"; then
   echo TRUE
fi