脚本是:
#!/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
输出的每一行读入数组的某种替代方式。有问题的创建数组的行是:
mapfile -t drives < <(lsblk --nodeps -o name,serial,size | grep "sd");
最佳答案
您可以遍历输入并追加到数组:
$ 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")'
或者,对于您的特定情况:
while IFS= read -r line; do
drives+=("$line")
done < <(lsblk --nodeps -o name,serial,size | grep "sd")
有关
IFS= read -r
是个好主意的详细说明,请参见BashFAQ/001:它可确保保留空格且不解释反斜杠序列。关于bash - 需要较早版本的Bash上的readarray/mapfile替代脚本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41475261/