Reputation: 63
Can somebody please explain the what below piece of shell script would be doing?
END_POS=$((${#column}-$COLON_INDEX))
Upvotes: 3
Views: 1005
Reputation: 289505
In this context, it stands for the the length of the value of that variable:
$ v="hello"
$ echo ${#v}
5
$ v="bye"
$ echo ${#v}
3
So what does this command?
END_POS=$((${#column}-$COLON_INDEX))
It gets the length of the value in $column
and substracts the value in $COLON_INDEX
using the $(( ))
syntax to perform arithmetic operations:
$ column="hello"
$ colon_index=2
$ r=$((${#column}-$colon_index)) # len("hello") - 2 = 5 - 2
$ echo $r
3
From Arithmetic expression:
(( )) without the leading $ is not a standard sh feature. It comes from ksh and is only available in ksh, Bash and zsh. $(( )) substitution is allowed in the POSIX shell. As one would expect, the result of the arithmetic expression inside the $(( )) is substituted into the original command. Like for parameter substitution, arithmetic substitution is subject to word splitting so should be quoted to prevent it when in list contexts.
Upvotes: 6
Reputation: 8769
All possible uses of #
that I can think of:
It stands for the length of the variable's value or element in case of arrays:
I have echoed variable's value length, array length and array's 1st index element's length:
$ var="abcd"
$ echo "${#var}"
4
$ arr=('abcd' 'efg')
$ echo "${#arr[@]}"
2
$ echo "${#arr[1]}"
3
$
Also $#
gives you the number of parameters passed to the script/function.
Upvotes: 2