Bash:通过用户输入获取数组值

时间:2017-04-23 12:59:24

标签: bash unix

我想输出一个带有文件名的数组,让用户选择要处理的文件。

目前我有以下内容:

patches=( $(ls $WORKING_DIR/PATCH_*) )
echo "Select available Patch to apply"
for i in "${!patches[@]}"; do
    echo  "$i"":" "${patches[$i]}"
done

echo "Line Number, followed by [ENTER]:"

read seleted_patch

echo "Patch to install:" "${patches[$selected_patch]}"

但是_PatchInstall_只输出patch数组的第一个值。 如何获取用户在命令行上输入的数组值?

2 个答案:

答案 0 :(得分:1)

很抱歉地说,但这只是一个错字。

尝试更改以下行:

read seleted_patch

要:

read selected_patch

答案 1 :(得分:1)

您可以使用select(专门为此目的设计的命令)

PS3= "Select available Patch to apply "
select patch in $WORKING_DIR/PATCH_*; do
    echo "Patch to install: $patch"
    break;
done

添加超出范围选择的处理

select patch in $WORKING_DIR/*; do
    if [[ ! $patch ]]; then
        echo "Selection out of range"
        continue
    fi
    if [[ $REPLY = 'q' ]]; then
        echo "Quit selection"
        break
    fi
    echo "Patch to install: $patch"
    break;
done