>我有这个 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会理解的。