Monday, July 4, 2011

Difference between $x and ${x}



   Many times in shell scripts we would have witnessed two different forms of notations being used against variables: $x and ${x}.  Are they both same or is there any difference between them? Let us discuss in this article:

Let us assign a value to the variable, x:
$ x=10

Now, lets try to display the value using both the above notations:
$ echo $x
10
Displaying using the second notation:
$ echo ${x}
10
  As seen above, it does not look like there is any difference. But it is not so. The actual difference we will see now:

Let us try to join or concatenate the literal "y" along with the value of $x:
$ echo $xy
 
   Nothing got printed for "echo $xy".  Now, let us the second notation to display:
$ echo ${x}y
10y
  What happened? When we said $xy, the shell interpreted it as being asked to print the value of a variable named "xy". Since there is no such variable "xy" being defined, a blank output. However, the second notation ${x}y is being interpreted as : print the value of x and concatenate it with the literal "y", and hence the result "10y".

2 comments:

  1. There's no difference between $x and ${x}. There *is* a difference between $xy and ${x}y, which is something entirely different.

    ReplyDelete
  2. Greetings, fellow UNIXhead! I really like your blog! There are only a few things that I would love to see improved, for instance it would be lovely to read these in order without having to go back to the main site each time, so a "next post" and "previous post" link on each post would be fantastic.

    The other thing is that it's not possible to comment on the blog itself, only on individual posts. That's the reason why this feedback seems a little random, I would have put it on your about page, but that wasn't possible. Though I suppose that is a limitation of blogspot rather than a conscious choice.

    Anyway, really love the blog, will be linking to it from my own site from now on! Can't wait for more updates!

    ReplyDelete