我在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”)
如何消除此错误?
答案 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有正确的答案。请注意,if
和then
之间可能有许多命令 - 这是有效的bash
if
echo hello world
ls
make
# etc etc etc
true
date
false
then
echo success
else
echo not success
fi
if命令的语法是:
if test-commands ;然后
随后的命令;
[elif more-test-commands ;然后
更后项;]
[else alternate-consequents ;]
网络执行 test-commands 列表,如果其返回状态为零,则执行 consequent-commands 列表。如果 test-commands 返回非零状态,则依次执行每个
elif
列表,如果其退出状态为零,则相应的更多结果执行并命令完成。如果存在“else alternate-consequents
”,并且最终if
或elif
子句中的最终命令具有非零退出状态,则 alternate-consequents 为执行。返回状态是执行的最后一个命令的退出状态,如果没有条件测试为真,则返回零。