unix 什么是错误的“语法错误接近意外的标记'fi'"?

dfty9e19  于 2022-11-04  发布在  Unix
关注(0)|答案(2)|浏览(203)

我不能处理这个问题。我运行脚本(我会在下面附上它),在第一个问题后,我得到错误“line 37 syntax error near unexpected token 'fi'如果fi被删除,什么都没有改变。帮助我理解...我尝试了许多解决方案,和dos2unix配置,并仔细检查了所有的缩进


# !/bin/bash

function pause (){
  read -p "Press any key to continue ... "
}
timedatectl set-timezone Atlantic/Reykjavik
a=`date +"%Y-%m-%d %H:%M:%S"`
echo -n -e "Current Date/Time is    " 
date
sleep 2
read -p "is it correct (Yes/No) ? " CC
  if [ "$CC" == "N" -o "$CC" == "n" ];then 
    echo "Exit testing ..."
    exit
  fi 
else
  read -p "Do you want to change (Yes/No) ? " CC
  if [ "$CC" == "Y" -o "$CC" == "y" ];then
    read -p "Please input new date, format: YYYYMMDD  " D
    NEWD="`echo $D | cut -b 1-4`"-"`echo $D | cut -b 5-6`"-"`echo $D | cut -b 7-8`"    
    read -p "Please input new time, format: HHMM   " T
    NEWT="`echo $T | cut -b 1-2`":"`echo $T | cut -b 3-4`":"00"    
    echo -n "date -s '" > d.sh
    echo -n "$NEWD $NEWT" >> d.sh
    echo "'" >> d.sh
    chmod 777 d.sh
    ./d.sh
    echo
    sleep 1
    clock -w
    sleep 1
    a=`date +"%Y-%m-%d %H:%M:%S"`
    echo -n -e "NEW Date/Time is""\e[0;32m $a\e[0m"", "
    read -p "Press ENTER to continue..."
  fi

UPD:enter image description here删除“else”后显示

UPD2***这是第二个出现相同错误的类似代码。另外,不要求输入信息(“请输入第一个MAC地址:")***

enter image description here

echo "************************"
echo "  Serial number setting "
echo "************************"

SLEN=0
while [ "$SLEN" != "13" ]
do 
read -p "Please input Serial Number:" sn
SLEN="${#sn}"
done

echo "*************************"
echo "   MAC-address setting   "
echo "*************************"

PLEN=0
until [ "$PLEN" == "12" ] && [ "$VID" == "0015B2" ]
do 
  read -p "Please input the First MAC address: " MACIN
  PLEN="${#MACIN}"
  if [ $PLEN != 12 ];then 
    echo
    echo MAC address LENTH error !!
  fi
  MAC=`echo $MACIN | tr a-z A-Z`
  VID=`echo $MAC | cut -b 1-6`
  if [ "$VID" != "0015B2" ];then
    echo
    echo -n "The first 6 digit MUST be"
    echo -n -e "\e[0;37;42m 0015B2 \e[0m", but you input 
    echo -e "\e[0;37;41m $VID \e[0m""!!" 
  fi
done
w41d8nur

w41d8nur1#

删除第一个if块后面的“else”,您的代码应该可以正常工作

mec1mxoz

mec1mxoz2#

最有可能的原因是脚本中有一个“外来的”(非ASCII)Unicode字符。像大多数脚本和编程语言一样,Bash不能容忍令牌中或令牌旁边存在非ASCII字符。
例如,在此语句中,then后面有一个空格:

if [ "$CC" == "N" -o "$CC" == "n" ];then

只要该空格是ASCII空格字符(U+0020),就可以这样做。如果该空格字符恰好是不间断空格(U+00 A0),则您将得到 * 完全 * 您所看到的错误:

Current Date/Time is    Thu Jul 21 16:39:09 WEDT 2022
is it correct (Yes/No) ? y
./test.sh: line 14: syntax error near unexpected token `fi'
./test.sh: line 14: `  fi '

这只是一个例子。还有更多的Unicode字符会导致这个问题。

  • 标记旁边或甚至 * 内的零宽度空格(U+200 B)。顾名思义,在大多数字体中该字符不可见。
  • 非ASCII字母;我记得有一个类似的问题,是因为在标识符中用西里尔字母E代替了罗马字母C。在许多字体中,这两个字母是无法区分的。

我强烈建议您使用一个十六进制查看器,并 * 非常仔细地 * 检查您的脚本中是否存在Unicode字符。

相关问题