2013-02-25 40 views
0

我想寫一個bash函數,它應該刪除table1中的一些條目,如果用戶輸入1,否則刪除不同的條目。我的功能看起來是這樣的:如何在bash中執行sqlplus?

function reset_db 
{ 
     if [ $usr_input == 1 ] 
     then 
     sqlplus -s $USR/[email protected]$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 
} 

我得到錯誤:附近意外的標記'科幻」

我相信,它正在發生,因爲我使用的if-else不正確的地方,但不是語法錯誤能夠找出解決方法。

也請讓我知道如果我有任何更多的後續問題,我怎麼能在同一個線程下發布代碼。

+0

請不要使用「謝謝」你的問題。這是無用的噪音。 – Doorknob 2013-02-25 19:47:10

回答

1

您需要if語句的每個子句中重複命令:

function reset_db 
{ 
     if [ $usr_input == 1 ] 
     then 
     sqlplus -s $USR/[email protected]$SID << EOF 

     delete from table1 where component = 'ABC'; 
     delete from table2 where component = 'ABC'; 
     exit 
EOF 
     elif [ $usr_input == 2 ]; then 

     sqlplus -s $USR/[email protected]$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/[email protected]$SID" <<EOF 
    delete from table1 where component = '$to_delete' 
    delete from table2 where component = '$to_delete' 
    exit 
EOF 
    fi 
} 
+0

謝謝。有一個精確的代碼是非常有用的。但是我有一些以'ABC'結尾的模式。例如:read_ABC,write_ABC,execute_ABC。如果我給出類似這樣的內容:'從table1中刪除組件='%\ _ $ to_delete'',那麼我得到「無效字符」錯誤。我怎樣才能做到這一點? – itsh 2013-02-25 23:24:59

+0

它將錯誤指向「%」。 '從upgrade_details'刪除其中組件=%_'ABC' * 錯誤在第1行: ORA-00911:無效字符0123: – itsh 2013-02-25 23:51:39

+1

使用綁定變量會更好。 – igr 2013-02-25 23:58:09

2

您'else if'錯了,正確的語法是'elif'。

+0

感謝您的快速回復。其實我用Java編程,現在我正在學習bash(這將是我的腳本語言)。所以我在語法上很難。不管怎樣,再次感謝。 – itsh 2013-02-25 20:01:33

+0

不客氣,如果能解決您的問題,請隨時接受答案;) – bagage 2013-02-26 18:43:18