Bash string concatenation producing weird results [duplicate]

强颜欢笑 提交于 2020-01-06 04:36:08

问题


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.



来源:https://stackoverflow.com/questions/46448604/bash-string-concatenation-producing-weird-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!