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
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++
orjava
. So when you write$A_new
shell considerA_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.This happens because the underscore is the valid character in variable names. Try this way: ${A}_new or "$A"_new
Shell variable names are composed of alphabetic characters, numbers and underscores.
So when you wrote
$A_new
the shell interpreted the underscore (andnew
) as part of the variable name and expanded the variableA_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 theA
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):
echo "${A}_new"
echo "$A"_new
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 doingecho "$A"\_new
but that's no different then point 2 ultimately so why bother.