1

I'm trying to concatenate two variables in linux tectia SSH into one variable, separated by "_". For some reason only one of the two variables is printed out.

I've tried to concatenate via " " e.g.:

sample1="$var1_$var2"

or

sample1="$var1 _ $var2"

and I've tried to concatenate directly e.g.:

sample1=$var1_$var2

Would appreciate any help given!

cnt_abr1=ab
cnt_abr2=cd
cnt_abr3=ef
env_abr1=a
env_abr2=b
sample1="$env_abr1_$cnt_abr1"
sample2=$env_abr2_$cnt_abr3
echo $sample1
echo $sample2

Output:

 _ ab
ef
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264

1 Answers1

1

Since underscores are effectively letters, bash has no way of knowing when your variable name ends and your literal underscore begins. The proper way to reference the variables is with ${...} in this case, which unambiguously delimits the name from the rest of the command line:

sample1="${env_abr1}_${cnt_abr1}"
sample2=${env_abr2}_${cnt_abr3}

In both cases, the second name does not require special treatment. Any other (semantically valid) non-letter character would do as well, as you pointed out in your comment:

sample1="$env_abr1"_"$cnt_abr1"
sample2="$env_abr2"_"$cnt_abr3"
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264