我正在尝试编写一个bash函数,如果用户输入1,则应删除table1中的某些条目,否则删除不同的条目。我的功能如下:
function reset_db
{
if [ $usr_input == 1 ]
then
sqlplus -s $USR/$pwd@$SID << EOF
delete from table1 where component = 'ABC';
delete from table2 where component = 'ABC';
exit
EOF
else if [ $usr_input == 2 ]
delete from table1 where component = 'XYZ';
delete from table2 where component = 'XYZ';
exit
EOF
fi
}
我收到错误:语法错误接近意外令牌`fi'
我确信它正在发生,因为我在某处使用if-else错误,但无法找到修复它的方法。
另外,如果我有更多跟进问题,请告诉我如何在同一个帖子下发布代码。
答案 0 :(得分:2)
你的'else if'错了,正确的语法是'elif'。
答案 1 :(得分:1)
您需要在if
语句的每个子句中重复该命令:
function reset_db
{
if [ $usr_input == 1 ]
then
sqlplus -s $USR/$pwd@$SID << EOF
delete from table1 where component = 'ABC';
delete from table2 where component = 'ABC';
exit
EOF
elif [ $usr_input == 2 ]; then
sqlplus -s $USR/$pwd@$SID << EOF
delete from table1 where component = 'XYZ';
delete from table2 where component = 'XYZ';
exit
EOF
fi
}
作为简化,你应该重构:
reset_db () {
if [[ $usr_input = 1 ]]; then
to_delete='ABC'
elif [[ $usr_input = 2 ]]; then
to_delete='XYZ'
else
return
fi
sqlplus -s "$USR/$pwd@$SID" <<EOF
delete from table1 where component = '$to_delete'
delete from table2 where component = '$to_delete'
exit
EOF
fi
}