【问题标题】:Reading MAC address to shell variable causes strange behavior将 MAC 地址读取到 shell 变量会导致奇怪的行为
【发布时间】:2025-12-03 16:00:02
【问题描述】:

我正在运行这个脚本

#!/bin/bash

if [ $# != 2 ]
then
   echo argument one must be the site number
   echo argument two must be the vlan
fi

site=$1
vlan=$2
deviceNum=1

while read MACLine
do
   echo arp -s 10.${site}.${vlan}.${deviceNum} "${MACLine}" temp
   deviceNum=`expr $deviceNum + 1`
done < MAC.txt

我用这个作为输入

AC:CC:8E:0A:EF:67
AC:CC:8E:0B:AE:4B
AC:CC:8E:0B:CF:17
00:40:8C:FC:6D:86
00:40:8C:FA:61:B1
AC:CC:8E:0F:B1:C3
AC:CC:8E:0B:E5:2B
AC:CC:8E:0F:B1:D7
AC:CC:8E:0F:B1:DF

我收到这个奇怪的输入...当我将粘贴复制到 Windows 中时(继续阅读)

arp -s 10.10.20.1 AC:CC:8E:0A:EF:67
 temp
arp -s 10.10.20.2 AC:CC:8E:0B:AE:4B
 temp
arp -s 10.10.20.3 AC:CC:8E:0B:CF:17
 temp
arp -s 10.10.20.4 00:40:8C:FC:6D:86
 temp
arp -s 10.10.20.5 00:40:8C:FA:61:B1
 temp
arp -s 10.10.20.6 AC:CC:8E:0F:B1:C3
 temp
arp -s 10.10.20.7 AC:CC:8E:0B:E5:2B
 temp
arp -s 10.10.20.8 AC:CC:8E:0F:B1:D7
 temp
arp -s 10.10.20.9 AC:CC:8E:0F:B1:DF
 temp

但是,在 Ubuntu shell 中,我看到以下内容

temps 10.10.20.1 AC:CC:8E:0A:EF:67
temps 10.10.20.2 AC:CC:8E:0B:AE:4B
temps 10.10.20.3 AC:CC:8E:0B:CF:17
temps 10.10.20.4 00:40:8C:FC:6D:86
temps 10.10.20.5 00:40:8C:FA:61:B1
temps 10.10.20.6 AC:CC:8E:0F:B1:C3
temps 10.10.20.7 AC:CC:8E:0B:E5:2B
temps 10.10.20.8 AC:CC:8E:0F:B1:D7
temps 10.10.20.9 AC:CC:8E:0F:B1:DF

这种疯狂的方法是什么?


注意:这与冒号有关。如果您将 MAC 地址替换为“hello...hello...hello”之类的内容,它会按预期工作

【问题讨论】:

  • 将你的脚本粘贴到shellcheck.net 那里你可以看到你有一些[不是决定性但重要的]警告
  • @fedorqui 我做了它建议的更正,但是,正如你自己所说的那样,他们没有解决问题
  • @Mr.Llama 你说得对,是dos格式的输入文件

标签: bash shell ubuntu for-loop


【解决方案1】:

您的输入文件中似乎有回车符。在输入文件上执行dos2unix 应该可以解决您的问题。

【讨论】:

  • 不,不是这样。我可以确认它是一个 UNIX 文件,即使调用 dos2unix,它仍然不起作用。
  • 伙计,我觉得自己很愚蠢......这是dos的输入文件。
  • 回车很不稳定。他们会将光标重置到行首并开始覆盖文本。这就是为什么您的输出行以temps 开头的原因,因为它被arp -s 覆盖了[space]temp
【解决方案2】:

这种疯狂被称为Windows。 我把你的 MAC 地址列表粘贴到 Ubuntu 上的一个文件中并运行脚本。

输出:

arp -s 10.10.20.1 AC:CC:8E:0A:EF:67 temp
arp -s 10.10.20.2 AC:CC:8E:0B:AE:4B temp
arp -s 10.10.20.3 AC:CC:8E:0B:CF:17 temp
arp -s 10.10.20.4 00:40:8C:FC:6D:86 temp
arp -s 10.10.20.5 00:40:8C:FA:61:B1 temp
arp -s 10.10.20.6 AC:CC:8E:0F:B1:C3 temp
arp -s 10.10.20.7 AC:CC:8E:0B:E5:2B temp
arp -s 10.10.20.8 AC:CC:8E:0F:B1:D7 temp
arp -s 10.10.20.9 AC:CC:8E:0F:B1:DF temp

然后转成windows狂,再次运行:

$ unix2dos MAC.txt
$ bash run_mac.sh 10 20
 temps 10.10.20.1 AC:CC:8E:0A:EF:67
 temps 10.10.20.2 AC:CC:8E:0B:AE:4B
 temps 10.10.20.3 AC:CC:8E:0B:CF:17
 temps 10.10.20.4 00:40:8C:FC:6D:86
 temps 10.10.20.5 00:40:8C:FA:61:B1
 temps 10.10.20.6 AC:CC:8E:0F:B1:C3
 temps 10.10.20.7 AC:CC:8E:0B:E5:2B
 temps 10.10.20.8 AC:CC:8E:0F:B1:D7
 temps 10.10.20.9 AC:CC:8E:0F:B1:DF

瞧……

【讨论】:

  • 我想unix2dos 命令是专门为这种情况创建的。