做为与列表循环,并使用该列表作为变量 [英] Doing for loop with a list and using the list as a variable

查看:184
本文介绍了做为与列表循环,并使用该列表作为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做了所有那些在我的电脑用户的循环,现在我试图让用户输入的数量,他们从用户名列表中,号码与用户名相关联,因此当用户选择像3的数它假设以示与号码相关联的用户名

 #!的/ usr / bin中/ env的庆典    数= $(awk的-F:'{$打印1}/ etc / passwd文件|厕所-l)    为((i = 1; I< = $号;我+ +))
    做
        在$用户名(AWK -F:'{$打印1}/ etc / passwd文件)
        做
            回声$ I名:$用户名
            如果[$ I== $号]
            然后
                #明确
                回声-ne输入号码:;阅读NUM
                如果[$ NUM==$ I]
                然后
                    回声您选择:$用户名
                科幻
            科幻
        DONE    DONE


解决方案

您可以使用特殊选择命令:

  PS3 =输入一个数字:
选择$名称(切-d:-f1 / etc / passwd文件);做
   如果[-n$ {}名];然后
      打破
   科幻
   回声对不起,请输入号码,如图所示。
DONE
回声从入口passwd是:$ {NAME}

I have made a for loop of all the users that are in my PC, and now I'm trying to make the user input the number they from the list of user names, and number is associated with a user name, so when the user chooses a number like 3 it's suppose to show the username associated with the number

#!/usr/bin/env bash



    number=$(awk -F: '{print $1}' /etc/passwd | wc -l )

    for ((i=1; i<=$number; i++))
    do
        for Username in $(awk -F: '{print $1}' /etc/passwd)
        do
            echo "$i Username: $Username"
            if [ "$i" == $number ]
            then
                #clear
                echo -ne "Enter a number: "; read num
                if [ "$num" == "$i" ] 
                then
                    echo "you chose: $Username"
                fi
            fi
        done 

    done

解决方案

You can use the special select command:

PS3="Enter a number: "
select name in $(cut -d: -f1 /etc/passwd) ; do
   if [ -n "${name}" ]; then
      break
   fi
   echo "Sorry, please enter a number as shown."
done
echo "Entry from passwd is: ${name}"

这篇关于做为与列表循环,并使用该列表作为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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