bashcase

Can't get variable assigned in Bash case statement


I need to be able to use a variable value that's assigned in a bash case statement. My input file has a single line.

30.xx.xx.xx,Bill

Here's my code

#!/bin/bash

MyList=IPlist.csv


while IFS=, read -r myIP UserName _
do

case $UserName in
  Tom)
      echo "Case is Tom and the IP address is $myIP..."
      UserName="Tom"
      echo "Username is $UserName"
      ;;
  Bill)
     echo "Case is Bill and the IP address is $myIP..."
     UserName="Bill"
     echo "Username is $UserName"
     ;;
  *)
     echo "Case is incorrect..."
     echo "Exiting line read...."
esac
done <$MyList
echo "$UserName"

This is the output I want

Tom@hostname ~
$ ./MyTest3.sh
Case is Bill and the IP address is 30.xx.xx.xx...
Username is Bill
Bill

Here's the output I'm getting

Tom@hostname ~
$ ./MyTest3.sh
Case is Bill and the IP address is 30.xx.xx.xx...
Username is Bill

I've been searching for the past hour and everything I find describes the code as I have it. I even checked shellcheck and it says "No errors detected!"

Thanks in advance for any help.

Edit - 5-11-24 I forgot to mention that his is a test of case. Ultimately I need read an 16,000 line comma delimited file and based on the username do snmpget to the devices to get the snmpv3 engineID. In case that makes any difference to the method used in the case statement.


Solution

  • The single line in the input file ends with a newline. Therefore, read tries to read the following line, too, but finds the EOF. When it tries to read the line, though, it clears all the variables it should populate.

    Solution: Don't use the same variable for input and result.

    #!/bin/bash
    
    MyList=IPlist.csv
    
    while IFS=, read -r myIP UserIn _
    do
        case $UserIn in
            Tom)
                echo "Case is Tom and the IP address is $myIP..."
                UserName="Tom"
                echo "Username is $UserName"
                ;;
            Bill)
                echo "Case is Bill and the IP address is $myIP..."
                UserName="Bill"
                echo "Username is $UserName"
                ;;
            *)
                echo "Case is incorrect..."
                echo "Exiting line read...."
        esac
    done <$MyList
    echo "$UserName"
    

    To debug the issue, I used set -xv at the start of the script. It showed me which lines were executing and what values were assigned to variables.