Error in string concatenation in shell scripts

I am starting to use shell scripts.

I used a variable to store the value A="MyScript"

. I have tried to concatenate the string in subsequent steps $A_new

. To my surprise it didn't work, and it $


Could you help me understand these details?



source to share

3 answers

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

Shell does not require variable declarations like in programming languages ​​like C

, C++

or java

. So when you write a shell $A_new

, consider it A_new

as a variable that you have not assigned any value to, so it is null.

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

It's always good practice to enclose variable names in curly braces after the sign $

to avoid this situation.



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

3.231 Name

In a shell command language, a word composed entirely of underscores, numbers, and alphabets from a portable character set. The first character of the name is not a digit.

So when you wrote $A_new

, the shell interpreted the underscore character (and new

) as part of the variable name and expanded the variable A_new


The period is not valid in the variable name, so when the shell parsed $

to expand the variable, it stopped in the period and expanded the variable A


The syntax ${A}

is for this to work as intended here.

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

  • echo "${A}_new"

  • echo "$A"_new

  • echo $A\_new

The latter is the least desirable because you cannot quote the entire line (or is \

not removed. Therefore, since you must always specify your variable expansions, you probably will echo "$A"\_new

, but this is no other than point 2 ultimately, so why bother ...



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



All Articles