-3

In Bash, I use a string where an arithmetic expression is expected:

$ (( hello ))
$ echo $?
1

$ echo $(( hello ))
0

$ let aaa=hello
$ echo $?
1
$ echo $aaa
0

There is no error reported. So is a string an arithmetic expression? If yes, is the value of a string always 0?

My question comes from a comment Why does command not work with a command beginning with assignment?

  • 1
    Where's the string? – Michael Homer Apr 23 '16 at 5:50
  • hello is the string. – Tim Apr 23 '16 at 5:55
  • 1
    hello is the variable name. – Michael Homer Apr 23 '16 at 5:57
  • See my edit. hello in the new example is a string, is it? – Tim Apr 23 '16 at 6:03
  • 7
    It's a variable name. – Michael Homer Apr 23 '16 at 6:04
5

In bash arithmetical expressions (e. g. $((3+2))), you can, just as with bash writ large, use variables. However, in this special case, you do not have to use the $ character to denote variables:

ghoti ~$ foo=5
ghoti ~$ echo $((foo))
5
ghoti ~$ echo $((foo*2))
10
ghoti ~$ echo $(($foo*2))
10

As mentioned in the comments to your question, hello in your case is not the string you think it is, but rather the name of an undefined variable which would have a value of zero.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.