Bash shell脚本:“意外令牌'fi'附近的语法错误”

时间:2017-07-17 20:06:10

标签: bash shell

我在bash shell脚本中有一段代码,看起来像这样,有一系列连续的条件:

#do January first, no matter what
awk '$4 == "Jan" {print $0}' < last-output.txt | sort -u -k1 > Jan.txt
awk -F'[ +:()]+' 'FNR==NR{a[$1]; next;} !($1 in a){next} NF==13{b[$1]+=$12/60+$11} NF==14{b[$1]+=$13/60+$12+24*$11} END{print "[Jan]"; for (n in b)print n,b[n],"hours"; print "\n"}' namelist Jan.txt > t1.txt
(IFS="|"; grep -vE "(${name_to_exclude[*]})" t1.txt > t1_new.txt)

#now iterate month by month for the rest of the months, up to the current month
if [ ${this_month} -ge 2]
        awk '$4 == "Feb" {print $0}' < last-output.txt | sort -u -k1 > Feb.txt
        awk -F'[ +:()]+' 'FNR==NR{a[$1]; next;} !($1 in a){next} NF==13{b[$1]+=$12/60+$11} NF==14{b[$1]+=$13/60+$12+24*$11} END{print "[Feb]"; for (n in b)print n,b[n],"hours"; print "\n"}' namelist Feb.txt > t2.txt
        (IFS="|"; grep -vE "(${name_to_exclude[*]})" t2.txt > t2_new.txt)
fi
if [ ${this_month} -ge 3]
        awk '$4 == "Mar" {print $0}' < last-output.txt | sort -u -k1 > Mar.txt
        awk -F'[ +:()]+' 'FNR==NR{a[$1]; next;} !($1 in a){next} NF==13{b[$1]+=$12/60+$11} NF==14{b[$1]+=$13/60+$12+24*$11} END{print "[Mar]"; for (n in b)print n,b[n],"hours"; print "\n"}' namelist Mar.txt > t3.txt
        (IFS="|"; grep -vE "(${name_to_exclude[*]})" t3.txt > t3_new.txt)
fi

持续到所有月份一直持续到12月。

当我尝试运行脚本时,我收到以下错误消息:

./login-act.sh: line 37: syntax error near unexpected token `fi'
./login-act.sh: line 37: `fi'

(第37行是第一次出现“fi”)

如何消除此错误?

2 个答案:

答案 0 :(得分:2)

then条件之后添加if并在]之前添加空格:

if [ ${this_month} -ge 2 ]; then
        awk '$4 == "Feb" {print $0}' < last-output.txt | sort -u -k1 > Feb.txt
        awk -F'[ +:()]+' 'FNR==NR{a[$1]; next;} !($1 in a){next} NF==13{b[$1]+=$12/60+$11} NF==14{b[$1]+=$13/60+$12+24*$11} END{print "[Feb]"; for (n in b)print n,b[n],"hours"; print "\n"}' namelist Feb.txt > t2.txt
        (IFS="|"; grep -vE "(${name_to_exclude[*]})" t2.txt > t2_new.txt)
fi

您可以在Bash conditional expressions[ builtin command以及[[ compound commmand上的Bash手册中找到更多信息。

答案 1 :(得分:1)

@Vadim有正确的答案。请注意,ifthen之间可能有许多命令 - 这是有效的bash

if
    echo hello world
    ls
    make
    # etc etc etc
    true
    date
    false
then
    echo success
else
    echo not success
fi

参考the bash manual

  

if命令的语法是:

     
    

if test-commands ;然后
    随后的命令;
    [elif more-test-commands ;然后
    更后项;]
    [else alternate-consequents ;]
    网络

  
     

执行 test-commands 列表,如果其返回状态为零,则执行 consequent-commands 列表。如果 test-commands 返回非零状态,则依次执行每个elif列表,如果其退出状态为零,则相应的更多结果执行并命令完成。如果存在“else alternate-consequents”,并且最终ifelif子句中的最终命令具有非零退出状态,则 alternate-consequents 为执行。返回状态是执行的最后一个命令的退出状态,如果没有条件测试为真,则返回零。