kobame
kobame

Reputation: 5856

Complicated bash variable syntax

In one bash script i found the next construction:

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

Can someone explain what the above condition does?

Upvotes: 2

Views: 174

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753695

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]}.

Upvotes: 4

Related Questions