Variable concatenate

Hello,

It might be stupid question But I will ask it any way:)

var1="1 2 3 4" 
var2="5 6 7 8"

var3=$var1\ $var2
var4="$var1\n$var2"

echo "$var1"
echo "$var2"
echo "$var3"
echo "$var4"

The result of executing this code is as follow
1 2 3 4
5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4\n5 6 7 8
Why the escape is not working, I want variable 4 to look like this
1 2 3 4
5 6 7 8
I change the code like this

var1="1 2 3 4" 
var2="5 6 7 8"

var3=$var1\ $var2
var4="$var1
$var2"

echo "$var1"
echo "$var2"
echo "$var3"
echo "$var4"

it worked but it is ugly.

Most likely your echo implementation needs an explicit option, in order to interpolate escape sequences:

$ echo \\n
\n
$ echo -e \\n

$

Hello,

I do not think it is related to echo. Usually I am using echo without any problem. I think it is related on how I concatenate the variables

var4="$var1\n$var2"

It's because you're using an escape sequence in the variable value.
Did you try to use the -e option?

$ v1=a v2=b v3="$v1\n$v2"
$ echo "$v3"
a\nb
$ echo -e "$v3"
a
b

echo's behavior and options vary between systems,
consider using printf for greater portability.

Alternatively consider using the POSIX version of the echo utility. See echo

Hello,

Thanks for the reply, and you are right. However this behavior cause a problem for me in another scenarios. it is not just only echo.
For example

var1="1 2 
1 2" 
var2="5 6 
7 8
7 8"
var3="$var1\n$var2"
var4=$(echo "$var3" | sort | uniq)
echo "$var4"

and now the result is
1 2
1 2\n5 6
7 8

and I want it to be

1 2
5 6
7 8

I can solve it as how I did in my first post but this is ugly, because I have the variables in different rows.

And why are you using a separate variables in the first place?
I would handle such a situation using an array, not scalar variables.

This is just a simple code, I use separate variable because I get them from different utilities such as a result of grep or sed and psql

You can still use arrays.
Which shell are you using?

I am using bash, for example I have something like that

var1 = $(grep....
var2 = $(psql

And I want to merge it together

How about

var4=$(printf "%s\n%s" $var1 $var2)

POSIX recommends that you do not use echo ; use printf instead.

---------- Post updated at 12:32 AM ---------- Previous update was at 12:27 AM ----------

printf -v var3 '%s\n%s' "$var1" "$var2" ## bash only
var3=$var1$'\n'$var2 ## bash, ksh93
## any shell
LF='
'
var3=$var1$LF$var2

etc. etc. ...

Thank you guy, I appreciate your help