LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Concatenate two variables with underscore - question (https://www.linuxquestions.org/questions/linux-newbie-8/concatenate-two-variables-with-underscore-question-812102/)

laki47 06-04-2010 04:24 AM

Concatenate two variables with underscore - question
 
Hi,

I have question regarding concatenation of two variables with underscore.

i.e. (bourne shell)

Code:

# var1=123
# var2=456
# echo $var1_$var2
sh: var1_: Parameter not set.
# echo $var1"_"$var2
# 123_456

My question is: What is the issue with underscore when I put it witout quotes? Why is it automatically concatenated to variable name (sh: var1_: Parameter not set.)?

Thanks!

grail 06-04-2010 04:35 AM

Quote:

What is the issue with underscore
The issue would be that it thinks the underscore is part of the variable name.
eg. think about
Code:

var=10

echo $varx

You would not expect this to work.
You can however use braces to clarify variable names:
Code:

var=10

echo ${var}x


laki47 06-04-2010 04:44 AM

But why will this work then:

Code:

# echo $var1-$var2
# 123-456

Why in this case the "-" is not concatenated?

David the H. 06-04-2010 05:02 AM

In the bash man page is a section on definitions.
Quote:

blank A space or tab.

word A sequence of characters considered as a single unit by the shell. Also known as a token.

name A word consisting only of alphanumeric characters and underscores, and beginning with an alphabetic character or an underscore. Also referred to as an identifier.

metacharacter A character that, when unquoted, separates words. One of the following: | & ; ( ) < > space tab

control operator A token that performs a control function. It is one of the following symbols: || & && ; ;; ( ) | |& <newline>
So the underscore is considered along with alphanumeric characters as being part of a "name", while others, such as the hyphen, are not.

By the way, here's a small trick you can use so that the underscore is only inserted if the second variable exists. Of course, it can only be used on shells that support this parameter substitution.

Code:

echo "${var1}${var2:+_}${var2}"

or more consisely:

echo "${var1}${var2:+_$var2}"



All times are GMT -5. The time now is 12:19 AM.