Linux Bash脚本没有正确打印出来

时间:2017-12-01 01:04:57

标签: linux bash

目标:我在此作业中的目标是创建一个脚本,该脚本将学生ID作为输入,并输出匹配的学生姓名或错误消息,表示此课程中没有该名称。我对Linux很新,对我来说有点难,但我会很乐意得到所有的帮助。谢谢!

Screenshot Page 1 of assignment

Screenshot Page 2 of assignment

我的脚本正在打印文件中的每个人名称,而不仅仅是我要搜索的名称。

  #!/bin/bash
# findName.sh
searchFile="/acct/common/CSCE215-Fall17"

if [[ $1 = "" ]] ; then
  echo "Sorry that person is not in CSCE215 this semester"
  exit 2
fi

while read LINE
do
    firstNameIndex=0
    middleNameIndex=1
    lastNameIndex=2
    userIDIndex=3

    IFS=', ' read -r -a lineArray <<< "$LINE"

        if [[ $1 -eq ${lineArray[$userIDIndex]} ]] ; then
        echo ${lineArray[$firstNameIndex]} ${lineArray[$middleNameIndex]} ${lineArray[$lastNameIndex]}
    fi

done < "$searchFile"

2 个答案:

答案 0 :(得分:0)

要更改的一行代码:

if [[ "$1" == "${lineArray[$userIDIndex]}" ]] ; then

答案 1 :(得分:0)

版本3:

以下是我如何用grep做的。这可以防止您循环输入文件。

#!/bin/bash

searchFile="sample.txt"

function notincourse()
{
    echo "Sorry that person is not in CSCE215 this semester"
    exit 2
}

# Verify arguments, 1 argument, name to search for
if [ $# -ne 1 ]
then
    echo "findName.sh <NAME>"
    exit 1
else
    searchfor=$1
fi

# Verify if the name is in the file
nameline=$(grep $searchfor $searchFile)
#if [ $(echo $nameline | wc -l) -eq 0 ]
if [ $? -eq 1 ]
then
    notincourse
else
    idvalue=$(echo $nameline | cut -d',' -f1)
    if [ "$idvalue" == "$searchfor" ]
    then
        IFS=', ' read -r -a lineArray <<< "$nameline"
        echo ${lineArray[1]} ${lineArray[2]} ${lineArray[3]}
    else
        notincourse
    fi
fi

我尝试使用以下测试输入文件:

111, firstname1, middlename1, lastname1
222, firstname2, middlename2, lastname2
333, firstname3, middlename3, lastname3

VERSION 3:它现在验证id确实是该行中的第一个单词。我意识到,如果他的名字中包含了学生ID(是的,但是比抱歉更安全!)我的grep将会返回true!