[英]Bash Scripting - Variable Concatenation
Completely new to Linux and Bash scripting and I've been experimenting with the following script:对 Linux 和 Bash 脚本完全陌生,我一直在尝试以下脚本:
declare -a names=("Liam" "Noah" "Oliver" "William" "Elijah")
declare -a surnames=("Smith" "Johnson" "Williams" "Brown" "Jones")
declare -a countries=()
readarray countries < $2
i=5
id=1
while [ $i -gt 0 ]
do
i=$(($i - 1))
rname=${names[$RANDOM % ${#names[@]}]}
rsurname=${surnames[$RANDOM % ${#surnames[@]}]}
rcountry=${countries[$RANDOM % ${#countries[@]}]}
rage=$(($RANDOM % 5))
record="$id $rname $rsurname $rcountry"
#record="$id $rname $rsurname $rcountry $rage"
echo $record
id=$(($id + 1))
done
The script above produces the following result:上面的脚本产生以下结果:
1 Liam Williams Andorra
2 Oliver Jones Andorra
3 Noah Brown Algeria
4 Liam Williams Albania
5 Oliver Williams Albania
but the problem becomes apparent when the line record="$id $rname $rsurname $rcountry"
gets commented and the line record="$id $rname $rsurname $rcountry $rage"
is active where the exact output on the second execution is:但是当行
record="$id $rname $rsurname $rcountry"
被注释并且行record="$id $rname $rsurname $rcountry $rage"
处于活动状态时,问题变得明显,其中第二次执行的确切 output 是:
4William Johnson Albania
2Elijah Smith Albania
2Oliver Brown Argentina
0William Williams Argentina
3Oliver Brown Angola
The file I am reading the countries from looks like this:我正在读取国家/地区的文件如下所示:
Albania
Algeria
Andorra
Angola
Argentina
Could you provide an explanation to why this happens?你能解释一下为什么会发生这种情况吗?
Your countries input file has DOS-style <cr><lf>
(carriage-return line-feed) line endings.您的国家/地区输入文件具有 DOS 样式的
<cr><lf>
(回车换行)行结尾。
When you read lines from the file, each element of the countries
array ends up looking like somename<cr>
, and when printed the <cr>
moves the cursor back to the beginning of the line, so the contents of $rage
end up overwriting the beginning of the line.当您从文件中读取行时,
countries
数组的每个元素最终看起来像somename<cr>
,并且在打印时<cr>
将 cursor 移回行首,因此$rage
的内容最终被覆盖行的开头。
The fix is to convert your countries input to use Unix style ( <lf>
only) line endings.解决方法是将您的国家/地区输入转换为使用 Unix 样式(仅限
<lf>
)行尾。 You can do this with dos2unix <inputfile> > <outputfile>
, for example.例如,您可以使用
dos2unix <inputfile> > <outputfile>
来执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.