Bash string concatenation producing weird results

2019-08-18 05:25发布

问题:

This question already has an answer here:

  • Concatenating strings in bash overwrites them 4 answers

My bash code file.sh :

username=$1
pkgpath="/home/${username}_tmp.txt"
echo $username
echo $pkgpath

Now running the script with the command bash file.sh abc should produce the result :

abc
/home/abc_tmp.txt

But the output I'm getting is :

abc
_tmp.txtc

Can someone explain why is this behavior occurring and how to obtain the desired result ?

EDIT
I'd like to mention that using pkgpath="/home/${username}" gives me /home/abc (desired) but running pkgpath="${username}_tmp.txt"gives me _tmp.txt(weird).

回答1:

Looks like you are somehow inserting a carriage return character after abc when you run the command bash file abc. The culprit is probably either your terminal, or you are copy pasting the command and are including ^M without realizing.

So what bash is outputting on the second line is really /home/abc^M_tmp.txt, which gets rendered as _tmp.txtc. You can easily verify this by piping the output of your command to less -R.