2012-05-01 39 views
1

我怎樣才能消除在命令行語法錯誤? 我創建了一個bash腳本是這樣的:如何消除命令行中的語法錯誤?

#!/bin/bash 

USER="[email protected]" 

sed 's/[[email protected]#\$%^&*()]//g'> [email protected] 
done 

if ! [ -f [email protected] -a -r [email protected] ] ; then 
echo "Wrong Option : "${USER}" is not readable or not exist" >&2 
exit -1 
fi 

cat "${@}"|while read -r line 
do 
IFS=, read -r f1 f2 f3 f4 f5 <<< "$line" 
mysql --user=user --password=password --database=database <<EOF 
INSERT INTO table_name VALUES($f1,'$f2','$f3','$f4',$f5); 
EOF 
done 

,我執行這個腳本在其他終端是這樣的:

$ ./script.sh test!rr.txt 
-bash: !rr.txt: event not found 

其實,這是插入來自文本文件中的數據以數據庫表的腳本。 ,正如你所看到的,我想之前插入文本文件,檢查文件是否存在。

我試圖使用TR -d命令和sed命令,以消除對命令行語法錯誤,但我認爲它不工作..

我的期望是:

$ ./script.sh test!rr.txt 
Wrong Option : test!rr.txt is not readable or not exist 

你有什麼想法? 謝謝。

回答

2

外殼被解釋!作爲歷史命令,試圖評估前行。嘗試逃脫它:在你的文件名

$ ./script.sh test\!rr.txt 
2

把雙引號,如果你想在它的bash特殊字符:

$ ./script.sh 'test!rr.txt' 
1

加上引號的參數,以防止shell解釋特殊符號:

$ ./script.sh "test!rr.txt" 
2

這是您需要調整您的期望的情況。 Bash只是做你告訴它做的事情:在將參數傳遞給腳本之前執行歷史擴展。關於引用參數或以其他方式轉義「!」的其他答案都是正確的,但是他們假設您意識到歷史擴展發生在參數傳遞到您的腳本之前(您可以檢查文件是否存在)。