无法在 Bash case 语句中分配变量

问题描述 投票:0回答:1

我需要能够使用 bash case 语句中分配的变量值。 我的输入文件只有一行。

30.xx.xx.xx,Bill

这是我的代码

#!/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"

这就是我想要的输出

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

这是我得到的输出

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

过去一个小时我一直在搜索,我找到的所有内容都描述了我拥有的代码。 我什至检查了 shellcheck,它说“未检测到错误!”

提前感谢您的帮助。

bash case
1个回答
0
投票

输入文件中的单行以换行符结尾。因此,

read
也尝试读取以下行,但发现了EOF。但是,当它尝试读取该行时,它会清除应填充的所有变量。

解决方案:不要对输入和结果使用相同的变量。

© www.soinside.com 2019 - 2024. All rights reserved.