简体   繁体   English

更聪明,更精简的方法来匹配Shell脚本中的输入变量?

[英]Smarter and more condensed method to match input variable in shell script?

I have a file with a list of numerous unique items, for this example I am using user ID's. 我有一个包含许多唯一项列表的文件,在此示例中,我使用的是用户ID。 The starting section of my script should display the list to the user running the script and allow them to chose one of the ID's. 我的脚本的开始部分应向运行脚本的用户显示该列表,并允许他们选择ID之一。 The script should then cross check the choice made by the user against the original file and if it matches it should provide a message advising of the match and continue with the script. 然后,脚本应对照原始文件对用户所做的选择进行交叉检查,如果匹配,则应提供一条消息,告知匹配情况并继续执行脚本。 If it does not match, the script should advise the user and exit. 如果不匹配,该脚本应建议用户并退出。

My current script does this OK, but I was wondering if there is any way to make it a bit smarter/more condensed, perhaps using arrays? 我当前的脚本可以执行此操作,但是我想知道是否有任何方法可以使它更智能/更简洁(也许使用数组)? Current script: 当前脚本:

This is my first post on this site so I apologies in advanced for any mistakes which have been made in the process of posting. 这是我在该网站上的第一篇文章,因此,对于在发布过程中发生的任何错误,我深表歉意。

FILE=testfile
IDLIST="$(awk '{print $1}' $FILE)"
echo "$IDLIST"
echo "\nSelect one of the options"
read input
OUTPUT="$(for i in $IDLIST
          do
               if [[ $i = $input ]]
                    then
                    echo "Matched."
               fi
          done)"

if [[ -z $OUTPUT ]]
    then
    echo "Invalid choice."
    exit 0
    else
    ID=$input
fi

echo "It is a match, continuing with script"

As you can imagine, there are many ways of doing this. 可以想象,有很多方法可以做到这一点。 One is using select instead: 一种是使用select代替:

PS3="Select an ID: "
select id in $(cut -d ' ' -f 1 testfile)
do
  [[ -z $id ]] && echo "Pick a number" || break
done
echo "You selected $id"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM