Prradep
Prradep

Reputation: 5716

Error in string Concatenation in Shell Scripting

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

Upvotes: 3

Views: 1649

Answers (3)

Inderdeep Singh
Inderdeep Singh

Reputation: 105

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.

Upvotes: 0

Rajesh
Rajesh

Reputation: 2155

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

Upvotes: 1

Etan Reisner
Etan Reisner

Reputation: 81002

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.

Upvotes: 3

Related Questions