包含for ... in循环的Bash脚本

时间:2018-03-02 08:26:29

标签: linux bash

我正在尝试让这个bash程序运行,但我似乎无法弄明白。我正在编写此脚本以获取名称列表并打印出每个名称组编号。我对bash很新,所以我不知道如何处理我的for语句中的变量GROUPNUM,以使该程序正常工作。例如,如果他们输入的用户名是Melissa,程序应该输出“Melissa,你在第20组。”我认为我的问题在于我的for循环中的变量GROUPNUM。任何帮助都会很棒,谢谢。

#!/bin/bash
echo "Please enter your first name: "
read NAME
for GROUPNUM in $(NAME)
do
case $NAME in
[a-H]*) echo "$NAME, you are in group 10"
;;
[i-M]*) echo "$NAME, you are in group 20"
;;
[n-Q]*) echo "$NAME, you are in group number 30"
;;
[r-Z]*) echo "$NAME, you are in group number 40"
;;
*) echo "Please enter valid input!"
;;
esac
done
echo "Goodbye!"

2 个答案:

答案 0 :(得分:1)

你有几件事值得怀疑。猜猜你想要做什么,这可能很接近:

#!/bin/bash

# This gives an infinite loop
while :
do
    echo "Please enter your first name: "
    # Changed NAME to name, uppercase can clash with shell variables
    read name

    # This breaks out of the infinite loop when the user hits <RETURN>
    [[ -z $name ]] && break

    # Note that I have changed the patterns to what I think you mean
    case $name in
        [a-hA-H]*) echo "$name, you are in group 10"
        ;;
        [i-mI-M]*) echo "$name, you are in group 20"
        ;;
        [n-qN-Q]*) echo "$name, you are in group number 30"
        ;;
        [r-zR-Z]*) echo "$name, you are in group number 40"
        ;;
        *) echo "Please enter valid input!"
        ;;
    esac
done
echo "Goodbye!"

答案 1 :(得分:0)

开始删除行
for
do

done

然后你会遇到下一个bug。但是不要没有理由使用循环。