2

In one bash script i found the next construction:

if [[ "${xvar[id]:0:${#cnt}}" != "$cnt" ]]; then

Can someone explain what the above condition does?

1
  • Another way to help understand is that it behaves identically to if [[ ${xvar[id]} = ${cnt}* ]]; then. Commented Sep 24, 2012 at 0:49

1 Answer 1

4

The complicated expression is: ${xvar[id]:0:${#cnt}}.

$xvar must be an array, possibly associative. If it is associative, the part ${xvar[id]} refers to the element of the array identified by the string 'id'; if not, then it refers to the element indexed by variable $id (you're allowed to omit the nested $), as noted by chepner in a comment.

The ${xxx:0:${#cnt}} part of the expression refers to a substring from offset 0 to the length of the variable $cnt (so ${#cnt} is the length of the string in the variable $cnt).

All in all, the test checks whether the first characters of ${xvar[id]} are the same as the value of $cnt, so is the value in $cnt a prefix of the value in ${xvar[id]}.

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

2 Comments

OMG. The substring part was the problematic one. Zilion thanx. ;)
xvar could be an indexed array as well; id could be a simple integer-valued parameter.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.