0

I have this bash 4.3 script:

#!/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

I get this error:

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

Does this have to do with the fact that I'm trying to use $i in the sub-loop? How do I use it globally (in the sub-loop)?

2
  • 2
    Use shellcheck.net Commented Jan 9, 2015 at 16:33
  • didn't know about shellcheck. thanks, @Cyrus Commented Jan 9, 2015 at 16:39

1 Answer 1

3

In the words of 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.

Your error is not a bash error, but an xmlstarlet error saying that it doesn't recognize $i. This makes sense because $i is a bash expression and not an xmlstarlet expression. If you use double quotes instead of single quotes, the $i will be replaced by its value, e.g. 0, which xmlstarlet will understand.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.