Reputation: 11569
My goal is to concatenate two strings.
Here's a copy-paste of my bash script:
str1="Hello"
str2="World"
str3=$str1$str2
echo $str3
The expected output is HelloWorld
but I'm getting World
instead.
It works fine when I run it in the terminal.
Here's the output when I run cat -v
on my script:
str1="Hello"^M
str2="World"^M
str3=$str1$str2^M
echo $str3^M
Am I missing something?
Upvotes: 2
Views: 1854
Reputation: 241848
That's probably because you have a carriage return (\r
) at the end of $str1
. I'm getting the same output with the following:
#!/bin/bash
str1="Hello"$'\r'
str2="World"
str3=$str1$str2
echo $str3
It often happens when you create the script on a MSWin machine.
It prints Hello, but then \r
moves the cursor back to the beginning of the line, and overwrites the Hello with World.
You can verify it by running it through a hex dump or cat -v
.
Upvotes: 6