需要较早版本的Bash上的readarray/mapfile替代脚本 [英] Need alternative to readarray/mapfile for script on older version of Bash
本文介绍了需要较早版本的Bash上的readarray/mapfile替代脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
脚本为:
#!/bin/bash
# Dynamic Menu Function
createmenu () {
select selected_option; do # in "$@" is the default
if [ 1 -le "$REPLY" ] && [ "$REPLY" -le $(($#)) ]; then
break;
else
echo "Please make a vaild selection (1-$#)."
fi
done
}
declare -a drives=();
# Load Menu by Line of Returned Command
mapfile -t drives < <(lsblk --nodeps -o name,serial,size | grep "sd");
# Display Menu and Prompt for Input
echo "Available Drives (Please select one):";
createmenu "${drives[@]}"
# Split Selected Option into Array and Display
drive=($(echo "${selected_option}"));
echo "Drive Id: ${drive[0]}";
echo "Serial Number: ${drive[1]}";
较旧的系统没有 mapfile
或 readarray
,因此我需要将该行转换为可以读取 lsblk每行的另一行.代码>输出到数组中.
The older system doesn't have mapfile
or readarray
so I need to convert that line to some alternative that can read each line of the lsblk
output into an array.
所讨论的创建数组的行是:
The line in question that creates the array is:
mapfile -t drives < <(lsblk --nodeps -o name,serial,size | grep "sd");
推荐答案
您可以遍历输入并追加到数组:
You can loop over your input and append to the array:
$ while IFS= read -r line; do arr+=("$line"); done < <(printf '%d\n' {0..5})
$ declare -p arr
declare -a arr='([0]="0" [1]="1" [2]="2" [3]="3" [4]="4" [5]="5")'
或者,对于您的具体情况:
Or, for your specific case:
while IFS= read -r line; do
drives+=("$line")
done < <(lsblk --nodeps -o name,serial,size | grep "sd")
请参见 BashFAQ/001 ,以很好地解释 IFS =为何读-r
是个好主意:它可确保保留空白且不解释反斜杠序列.
See the BashFAQ/001 for an excellent explanation why IFS= read -r
is a good idea: it makes sure that whitespace is conserved and backslash sequences not interpreted.
这篇关于需要较早版本的Bash上的readarray/mapfile替代脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文