3

I am beginner to Shell scripting.

I have used a variable to store value A="MyScript". I tried to concatenate the string in subsequent steps $A_new. To my surprise it didn't work and $A.new worked.

Could you please help me in understanding these details?

Thanks

Prradep
  • 5,506
  • 5
  • 43
  • 84
  • Does the info in [this question](http://stackoverflow.com/questions/4181703/how-can-i-concatenate-string-variables-in-bash) help? – Michael Scarn May 07 '15 at 01:31
  • @MichaelScarn though it was not I was looking for but thanks for sharing such nice information. – Prradep May 07 '15 at 18:46

3 Answers3

3

Shell variable names are composed of alphabetic characters, numbers and underscores.

3.231 Name

In the shell command language, a word consisting solely of underscores, digits, and alphabetics from the portable character set. The first character of a name is not a digit.

So when you wrote $A_new the shell interpreted the underscore (and new) as part of the variable name and expanded the variable A_new.

A period is not valid in a variable name so when the shell parsed $A.new for a variable to expand it stopped at the period and expanded the A variable.

The ${A} syntax is designed to allow this to work as intended here.

You can use any of the following to have this work correctly (in rough order of preferability):

  1. echo "${A}_new"
  2. echo "$A"_new
  3. echo $A\_new

The last is least desirable because you can't quote the whole string (or the \ doesn't get removed. So since you should basically always quote your variable expansions you would end up probably doing echo "$A"\_new but that's no different then point 2 ultimately so why bother.

Community
  • 1
  • 1
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
1

This happens because the underscore is the valid character in variable names. Try this way: ${A}_new or "$A"_new

Rajesh
  • 2,135
  • 1
  • 12
  • 14
0

The name of a variable can contain letters ( a to z or A to Z), numbers ( 0 to 9) or the underscore character ( _).

Shell does not require any variable declaration as in programming languages as C , C++ or java. So when you write $A_new shell consider A_new as a variable, which you have not assigned any value therefore it comes to be null.

To achieve what you mentioned use as : ${A}_new

Its always a good practice to enclose variable names in braces after $ sign to avoid such situation.

Inderdeep Singh
  • 105
  • 1
  • 9