为什么我的 echo 命令会在彼此之上写两个字?

Why is my echo command writing two words over each other?

我有一个 bash 脚本,它选择两个单词并(应该)连接它们。

#!/bin/bash

adj="$(shuf -n1 adjectives.txt)"
noun="$(shuf -n1 nouns.txt)"

echo ADJ $adj
echo NOU $noun

echo "$adj $noun"

变量设置正确,但由于某种原因,最终回显不正确。例如:

ADJ humbler
NOU lyric
 lyricr

或者:

ADJ bipinnate
NOU lipases
 lipasese

这里发生的是,最终输出是形容词在名词末尾的最后一个字母。为什么会这样,我该如何阻止它?

这里有一个关于这种现象的Asciinema:https://asciinema.org/a/199297

您的输入文件很可能有 CRLF (\r\n) 行结尾。 \r(回车符 return)将导致输出跳回到当前行的第一列,因为您的连接摆脱了 \n 而不是 \r .

这是Windows/DOS使用的格式。

您可以转换文件,也可以使用 tr 将其删除,例如:

adj="$(shuf -n1 adjectives.txt | tr -d '\r')"
noun="$(shuf -n1 nouns.txt | tr -d '\r')"

您也可以 运行 跨文件,例如:

tr -d '\r' < adjectives.txt > adjectives-reformatted.txt