就像标题所说的那样。尝试从 zenity checklist 输出填充数组。这是我想运行但失败的函数:
function fSongType() {
mType=$(zenity --list --title "Random song list generator" --text "Enter path from which to randomly choose songs:" --width="300" --height="360" --radiolist --column "Pick" --column "Music type" --print-column=2 FALSE All FALSE Baby FALSE Children FALSE "Easy Peasy" FALSE Holiday FALSE Instrumental FALSE "Rock Classics" TRUE "Rock Next Gen" FALSE "Rock Next Gen Heavy" FALSE "Rock Next Gen Light" FALSE "Rock Pop" FALSE Spiritual FALSE Thai|sed -r 's/[ ]{1,}//g') ; echo "\$mType: ${mType}"
# create an array for the output of user checklist input returned to var '$mType"
mTypeAr=()
cntr=0
until [[ -z "$mType" ]] ; do
mTypeAr+=$(echo "$mType"|sed -r 's/^[|]{0,1}([a-zA-Z]*)[|]{0,1}.*$/\1/') ; echo "\$mTypeAri[$cntr]: ${mTypeAr[$cntr]}"
mType=$(echo "$mType"|sed -r 's/^[|]{0,1}[a-zA-Z]*(|.*)$/\1/') ; echo "\$mType: ${mType}"
((cntr++))
done
}
后续终端输出:
${mTypeAr[0]}: Instrumental|RockClassics|RockNextGen|RockClassics|RockNextGen|RockNextGenInstrumentalRockClassics|RockNextGenRockClassicsRockNextGenRockNextGenInstrumentalRockClassics|RockNextGen
$mType: |RockClassics|RockNextGen
${mTypeAr[1]}:
$mType: |RockNextGen
${mTypeAr[2]}:
$mType:
因此,由于未知的原因(对我来说),zenity 输出全部分配给数组中的第一个元素。但如果我改为使用 '$cntr' 变量修改数组分配,则数组元素将按预期填充。
# create an array for the output of user checklist input returned to var '$mType"
mTypeAr=()
cntr=0
until [[ -z "$mType" ]] ; do
mTypeAr["$cntr"]=$(echo "$mType"|sed -r 's/^[|]{0,1}([a-zA-Z]*)[|]{0,1}.*$/\1/') ; echo "\$mTypeAri[$cntr]: ${mTypeAr[$cntr]}"
mType=$(echo "$mType"|sed -r 's/^[|]{0,1}[a-zA-Z]*(|.*)$/\1/') ; echo "\$mType: ${mType}"
((cntr++))
done
后续终端输出:
$mType: Instrumental|RockClassics|RockNextGen
${mTypeAr[0]}: Instrumental
$mType: |RockClassics|RockNextGen
${mTypeAr[1]}: RockClassics
$mType: |RockNextGen
${mTypeAr[2]}: RockNextGen
$mType:
一旦一切按预期运行,我希望丢失 '$cntr' 变量和 echo。我确信问题很明显,只是我忽略了;但如果我看不出来,那就太糟糕了。任何帮助都感激不尽。
答案1
array+=string
将“字符串”附加到数组的第一个元素;要将其添加为新元素,请使用array+=(string)
。在您的函数中,这意味着使用:
mTypeAr+=($(echo "$mType"|sed -r 's/^[|]{0,1}([a-zA-Z]*)[|]{0,1}.*$/\1/'))