Print two variables in one line

6,171

Solution 1

for i in 1 2; do
  echo variable${i}_case$i
done

should do what you want. Substitute 1 2 with the numbers or strings you need. Dependent on the values of $i you may need to quote it like so: echo variable"$i"_case"$i".

Solution 2

I assume the problem in your script is that you try to embed the variable names directly inside a text string, so that they are followed by other characters which could be part of a variable name. These do not only include alphanumeric characters but also the underscore.

So if you want to embed variables into a string in a way so that they are not separated from the rest by spaces or any non-variable-name characters, you can use the variable name notation with curly braces instead:

$ i=42
$ echo "variable${i}_case${i}."
variable42_case42.
Share:
6,171

Related videos on Youtube

Ka_Papa
Author by

Ka_Papa

Updated on September 18, 2022

Comments

  • Ka_Papa
    Ka_Papa over 1 year

    I wanted two print to variables in one line. I am using a shell script #!/bin/sh loop and what I wanted to do is a for repeat which prints out something like:

    variable1_case1
    variable2_case2
    

    and I have already tried

    variable$i_case$i.
    
    • Zanna
      Zanna over 6 years
      show us your script please...
  • derHugo
    derHugo over 6 years
    This answer is not complete but better referring to the echo .. line
  • dessert
    dessert over 6 years
    I doubt the dot is wanted, but if so it can't be part of a variable name, therefore echo ${i}_$i. works fine.
  • derHugo
    derHugo over 6 years
    Yes, as long there is no further output wanted after the string it works. Therefore I'ld say this answer cover general cases and is therefore better. But anyway the OP made his decision ;)
  • Byte Commander
    Byte Commander over 6 years
    @dessert Yes, you're absolutely right that $i. would be valid as well. I just think that if it is reasonable, the writing style should be consistent across one command. That leaves less room for mistakes.
  • dessert
    dessert over 6 years
    @ByteCommander You got a point there.