如何让用户从数组中选择一个值并将其传递给KSH中的变量 [英] How to have a user select a value from array and pass that into a variable in KSH

查看:116
本文介绍了如何让用户从数组中选择一个值并将其传递给KSH中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

概述:
我希望我的KSH脚本测试目录中是否存在某些文件,向用户提供这些文件的列表以及数字.然后,用户选择所需的数字,并将数组中的相关值分配给变量.

Overview:
I would like my KSH script to test for the presence of certain files in a directory, present the user with a list of those files along with a number. The user then chooses the number they want and the relevant value from the array is assigned to a variable.



到目前为止,我有以下内容:



So far I have the following:

### Create test files in directory ####
touch ABCDEF.jar
touch BCDEFG.jar
touch CDEFGH.jar
touch DEFGHI.jar
touch EFGHIJ.jar
touch FGHIJK.jar
touch GHIJKL.jar


set -A JARS ` ls -1 | grep .jar | cut -d'.' --complement -f2-`
for i in ${JARS[@]}; do echo "Number) $i"; done

这将从数组中返回以下列表:

This returns the following list from the array:

Number) ABCDEF
Number) BCDEFG
Number) CDEFGH
Number) DEFGHI
Number) EFGHIJ
Number) FGHIJK
Number) GHIJKL

首先,我想将占位符(Number)"替换为一个函数,该函数按顺序增加数字以得到如下内容:

Firstly, I'd like to replace the place holder "Number)" with a function which increases the number in sequence to get something like this:

1) ABCDEF
2) BCDEFG
3) CDEFGH
4) DEFGHI
5) EFGHIJ
6) FGHIJK
7) GHIJKL

然后我想让脚本根据用户选择的Number读取用户输入,然后将数组中的正确值分配给新变量"JAR_ID"

I'd then like to have the script read the user input based on the Number the user has chosen, and assign the correct value from the array to a new variable "JAR_ID"



从表面上看,这似乎是一个简单的问题.但是,我似乎无法理解如何以合乎逻辑的方式做到这一点.



On the face of it, it seems like a simple problem. However, I just can't seem to get my head round how to do this in a logical way.

感谢任何想法!

TIA 哈斯基.

推荐答案

如果您不介意列表中的完整文件名,则可以使用.

If you don't mind the full filenames in the list then just this will work.

select JAR in *.jar; do
        export NEW_PATCHID=$JAR
        echo $NEW_PATCHID
        REPLY=''
        break
done

如果您确实介意(示例表明您可能)并且想要删除.jar(我假设这就是cut的含义,尽管cut -d. -f1似乎比awk -F . '{print $1}'更为简单)尽管时间更长),但以下内容可以安全地工作.

If you do mind (and the example indicates you might) and you want to drop .jar (I'm assuming that's what that cut is for though cut -d. -f1 would seem simpler for that as would awk -F . '{print $1}' though that is longer) the following works safely.

jars=(*.jar)
select JAR in "${jars[@]%.jar}"; do
        export NEW_PATCHID=$JAR
        echo $NEW_PATCHID
        REPLY=''
        break
done

这篇关于如何让用户从数组中选择一个值并将其传递给KSH中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆