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

2
  • Does the info in this question help? Commented May 7, 2015 at 1:31
  • @MichaelScarn though it was not I was looking for but thanks for sharing such nice information. Commented May 7, 2015 at 18:46

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is exact explanation for your query. Also you can specify explicitly by any of the mentioned ways : 1. ${A}_new 2. $A\_new
Thank you @Etan for your detailed answer. It clears my doubt and concepts.
1

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

3 Comments

Ya. $A_new, in fact, is ${A_new}.
You mean ${A}_new not {$A}_new.
Thanks @Rajesh. I didn't get your statement Robin.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.