SH: Don't know how to refer to this ... :P

9.0 REL
Code:
test_num=8

#  This is the way it is supposed to be used
#res=$((63 * "$[color="DarkRed"]test_num[/color]"))

# However, refering to var "this" way, works! And it wasn't supposed to! :P
res=$((63 * [color="darkred"]test_num[/color]))

echo "$res"

Am I missing something here?
 
Code:
res=$((63 * $test_num))
works fine, as does
Code:
res=$((63 * ${test_num}))

By the way, your first code did work in a regular sh shell. E.g. mksh complained about the quotes though, and bash didn't like it either.
 
Man, you've totally missed a point here
Look at what I've posted, with great care ...
Code:
res=$((63 * test_num))
Variable test_num doesn't have a preceding $ and that raw string evaluates to a value which holds var $test_num.

Forget quotes and {} form, as $ is mandatory to refer to variable's value!
 
Seeker said:
$ is mandatory to refer to variable's value!
Apparently not inside an expression.

Code:
dice@vps-2417-1:~>sh
$ test_num=8
$ echo $test_num
8
$ test_num
test_num: not found
$ $((test_num))
8: not found
$ $((8 * test_num))
64: not found
$
 
Well that is what I'm talking about. It violates how variables work in sh. What interests me now, is this a bug or intended behavior (in which case this is a first time I've ever heard about this).
 
You get the same behaviour on RHEL (which actually uses bash):
Code:
sh-3.2# test_num=8
sh-3.2# echo $test_num
8
sh-3.2# $((test_num))
sh: 8: command not found

Solaris 8,9 and 10 don't like it at all:
Code:
$ test_num=8
$ echo $test_num
8
$ $((test_num))
syntax error: `$' unexpected
$ $(( 8 * test_num ))
syntax error: `$' unexpected
$ $(( $test_num ))
syntax error: `$' unexpected
 
Variables without a $ in arithmetic are documented behaviour (see Arithmetic Expansion in sh(1)()) and required by POSIX.

Also, variables can be assigned new values. For example, a variable can be incremented without mentioning its name twice:

Code:
: $((very_long_name += 1))

The ++ and -- operators are not required by POSIX, and are not provided.

The text about double-quotes in the man page reflects the POSIX requirement. In other words, it says that a double-quote does not terminate the arithmetic expression but is a literal part of the expression. It may be expected that this leads to a syntax error because string constants are not part of the subset of C that arithmetic expressions are. In some shells this is indeed the case. However, in FreeBSD 9 sh double-quotes are simply ignored for compatibility reasons and in older versions they introduce some form of quoting (which is not useful).
 
Thanks. I didn't know that.
Also, this incrementing feature and others from "saving mentioning var name twice" group work only without prepended $
Code:
tvar=5

#echo $(("$tvar" += 5))
#echo $(($tvar += 5))
    # Both errors with: 'arithmetic expression: expecting EOF: "5 += 5"'

# 10
echo $((tvar += 5))
 
Back
Top