LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   [SOLVED] Bash: how does this $[ ] code snippet work? (http://www.linuxquestions.org/questions/programming-9/%5Bsolved%5D-bash-how-does-this-%24%5B-%5D-code-snippet-work-753852/)

catkin 09-09-2009 07:53 AM

[SOLVED] Bash: how does this $[ ] code snippet work?
 
Hello :)

Why does bash do this
Code:

c@CW8:~$ a=b
c@CW8:~$ b=c
c@CW8:~$ c=d
c@CW8:~$ set -o nounset
c@CW8:~$ echo $[a]
bash: d: unbound variable
c@CW8:~$ set +o nounset
c@CW8:~$ echo $[a]
0
c@CW8:~$ echo $[a+1]
1

Best

Charles

RaptorX 09-09-2009 08:12 AM

hi catkin!

An unbound variable is one that has not been defined.

So lets review something...

Code:

[~]$ a=b
[~]$ echo $a
b
[~]$ echo ${a}
b
[~]$ echo $[a]
0

The only time i have seen [] in variables is in arrays like a[0] so maybe $[] is referencing a non existent array and is giving you the value 0.

If you are trying to reference to the "d" through "a" then i guess this would do the trick:

Code:

a=letter  # Variable "a" holds the name of another variable.
letter=z

echo

# Direct reference.
echo "a = $a"          # a = letter

# Indirect reference.
  eval a=\$$a
# ^^^        Forcing an eval(uation), and ...
#        ^  Escaping the first $ ...
# ------------------------------------------------------------------------
# The 'eval' forces an update of $a, sets it to the updated value of \$$a.
# So, we see why 'eval' so often shows up in indirect reference notation.
# ------------------------------------------------------------------------
  echo "Now a = $a"    # Now a = z

Now, remember that i am not an expert and this is just what i can see from the outside. :D

Im still learning.

catkin 09-09-2009 12:34 PM

Thanks RaptorX :)

Solved it! After intensive netsearching (not helped by Google ignoring string "$[" in searches!) the bash man page gave the answer:
Code:

  Arithmetic Expansion
      Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result.  The format  for  arithmetic  expansion
      is:

              $((expression))

      The old format $[expression] is deprecated and will be removed in upcoming versions of bash.

Best

Charles


All times are GMT -5. The time now is 01:56 PM.