bash 中未声明的变量(如何在子循环中使用变量)

undeclared variable in bash (how to use variable in sub-loop)

我有这个 bash 4.3 脚本:

#!/bin/bash

for x in *.xml; do
  badid=$(xml sel -t -v "//bad/@id" "$x")
  vg=${badid%\.*}
  count=$(xml sel -t -v 'count(//bad/objdesc/desc/@id)' "$x")
  for ((i=1; i<=count; i++)); do
    id=$(xml sel -t -v "//bad/objdesc/desc[$i]/@id" "$x")
    count2=$(xml sel -t -v 'count(//bad/objdesc/desc[$i]/objtitle/objid/objcode/@code)' "$x")
    for ((j=1; j<=count2; j++)); do
        bentleynum=$(xml sel -t -v "//bad/objdesc/desc[$i]/objtitle/objid/objcode[$j]/@code" "$x")
        if [[ $bentleynum == B* ]]; then break; else continue; fi
    done
    cat<<EOF
$vg.$bentleynum $id
EOF
  done
done

我收到这个错误:

runtime error: element call-template
Variable 'i' has not been declared.
xmlXPathCompiledEval: 1 objects left on the stack.

这是否与我试图在子循环中使用 $i 有关?如何全局使用它(在子循环中)?

用shellcheck的话来说:

count2=$(xml sel -t -v 'count(//bad/objdesc/desc[$i]/objtitle/objid/objcode/@code)' "$x")
                       ^-- SC2016: Expressions don't expand in single quotes, use double quotes for that.

您的错误不是 bash 错误,而是 xmlstarlet 错误,表明它无法识别 $i。这是有道理的,因为 $i 是 bash 表达式而不是 xmlstarlet 表达式。如果您使用双引号而不是单引号,则 $i 将被其值替换,例如0,哪个xmlstarlet就懂了