Anuradha singh Anuradha singh - 2 years ago 68
Bash Question

What is meaning of '#' before a variable in shell script?

Can somebody please explain the what below piece of shell script would be doing?


Answer Source

In this context, it stands for the the length of the value of that variable:

$ v="hello"
$ echo ${#v}

$ v="bye"
$ echo ${#v}

So what does this command?


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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download