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

时间:2015-01-09 16:24:12

标签: bash global-variables

我有这个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的事实有关?我如何全局使用它(在子循环中)?

1 个答案:

答案 0 :(得分:3)

用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将理解。