Bash string concatenation producing weird results

2019-08-18 05:48发布

This question already has an answer here:

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条回答
Root(大扎)
2楼-- · 2019-08-18 05:58

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.

查看更多
登录 后发表回答