在旧版本的Bash上需要替换readarray/mapfile以获取脚本

Jos*_*man 2 unix bash shell

该脚本是:

#!/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]}";
Run Code Online (Sandbox Code Playgroud)

旧系统没有mapfile或者readarray我需要将该行转换为可以将lsblk输出的每一行读入数组的替代方案.

创建数组的问题是:

mapfile -t drives < <(lsblk --nodeps -o name,serial,size | grep "sd");
Run Code Online (Sandbox Code Playgroud)

Ben*_* W. 6

您可以循环输入并附加到数组:

$ 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")'
Run Code Online (Sandbox Code Playgroud)

或者,针对您的具体情况:

while IFS= read -r line; do
    drives+=("$line")
done < <(lsblk --nodeps -o name,serial,size | grep "sd")
Run Code Online (Sandbox Code Playgroud)

请参阅BashFAQ/001以获得一个很好的解释,为什么这IFS= read -r是一个好主意:它确保空白是守恒的,反斜杠序列不被解释.