gpt4 book ai didi

bash - 在旧版本的 Bash 上需要替代 readarray/mapfile 的脚本

转载 作者:行者123 更新时间:2023-11-29 09:39:28 24 4
gpt4 key购买 nike

脚本是:

#!/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]}";

旧系统没有mapfilereadarray所以我需要将该行转换为可以读取 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")

参见 BashFAQ/001对于为什么 IFS= read -r 是一个好主意的一个很好的解释:它确保保留空格并且不解释反斜杠序列。

关于bash - 在旧版本的 Bash 上需要替代 readarray/mapfile 的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41475261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com