Error in string Concatenation in Shell Scripting

2019-02-25 07:32发布

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

标签: shell unix
3条回答
Explosion°爆炸
2楼-- · 2019-02-25 08:07

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.

查看更多
走好不送
3楼-- · 2019-02-25 08:13

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

查看更多
Ridiculous、
4楼-- · 2019-02-25 08:25

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.

查看更多
登录 后发表回答