Bash 字符串连接产生奇怪的结果 [英] Bash string concatenation producing weird results

查看:52
本文介绍了Bash 字符串连接产生奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 bash 代码 file.sh :

My bash code file.sh :

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

现在使用命令 bash file.sh abc 运行脚本应该会产生结果:

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

abc
/home/abc_tmp.txt

但我得到的输出是:

abc
_tmp.txtc

有人可以解释为什么会发生这种行为以及如何获得所需的结果吗?

编辑
我想提一下,使用 pkgpath="/home/${username}" 给我 /home/abc (desired) 但运行 pkgpath="${username}_tmp.txt" 给了我 _tmp.txt(奇怪).

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).

推荐答案

当您运行命令 bash file abc 时,您似乎以某种方式在 abc 后插入了一个回车符>.罪魁祸首可能是您的终端,或者您正在复制粘贴命令并在没有意识到的情况下包含 ^M.

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.

所以 bash 在第二行输出的实际上是 /home/abc^M_tmp.txt,它被渲染为 _tmp.txtc.您可以通过将命令的输出通过管道传送到 less -R 来轻松验证这一点.

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.

这篇关于Bash 字符串连接产生奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆