我正在编写一个用于随机预测的脚本,但不幸的是,该脚本并没有从两个随机列表(事物和效果)中获取整行,而是从每个列表中打印一个随机单词。有人可以告诉我如何让脚本从两个列表中打印整行吗?以下是我的脚本:
#!/bin/bash
# Random lists picks
# This is a script for picking random choices as a prediction.
Things="Walk
Song
Talk
Friend
Spontaneous act
Call"
Effects="will bless you
will lift your spirit
is healthy
can help
will touch you
will make you smile
is what what you need
makes a difference in your life
can add comfort
isn't necessarily without virtue
adds something to your day"
things=($Things)
effects=($Effects)
num_things=${#things[*]}
num_effects=${#effects[*]}
echo -n " A ${things[$((RANDOM%num_things))]} "
echo ${effects[$((RANDOM%num_effects))]}
答案1
在从变量创建数组时,您需要将IFS
(内部字段分隔符) 变量设置bash
为换行符,以便变量的每个换行符分隔条目都将被视为数组元素。在您的主脚本中,数组是根据默认值(即空格、制表符和换行符)\n
分隔的变量条目创建的。IFS
简而言之,您需要将这两个数组声明行更改为:
IFS=$'\n' things=( $Things )
IFS=$'\n' effects=( $Effects )
因此,你的最终脚本是:
#!/bin/bash
# Random lists picks
# This is a script for picking random choices as a prediction.
Things="Walk
Song
Talk
Friend
Spontaneous act
Call"
Effects="will bless you
will lift your spirit
is healthy
can help
will touch you
will make you smile
is what what you need
makes a difference in your life
can add comfort
isn't necessarily without virtue
adds something to your day"
IFS=$'\n' things=( $Things )
IFS=$'\n' effects=( $Effects )
num_things=${#things[*]}
num_effects=${#effects[*]}
echo -n "A ${things[$((RANDOM%num_things))]} "
echo "${effects[$((RANDOM%num_effects))]}"
答案2
我认为您对数组的使用有一点误解。
#!/bin/bash
# Random lists picks
# This is a script for picking random choices as a prediction.
# Create array "things"
things=('Walk'
'Song'
'Talk'
'Friend'
'Spontaneous act'
'Call')
# Create array "effects"
effects=('will bless you'
'will lift your spirit'
'is healthy'
'can help'
'will touch you'
'will make you smile'
'is what what you need'
'makes a difference in your life'
'can add comfort'
"isn't necessarily without virtue"
'adds something to your day')
# Place the array size
num_things=${#things[@]}
num_effects=${#effects[@]}
echo -n " A ${things[$((RANDOM%num_things))]} "
echo "${effects[$((RANDOM%num_effects))]}"