2016-12-08 43 views
-1

我已經編寫了基於某個日期條件的清理活動腳本。但我得到一個錯誤。Bash - 語法錯誤:文件意外結束

#!/bin/bash 
echo "Process Started" 
Current_Date=`date +%Y-%m-%d` 
echo "todays Date ==> $Current_Date" 
fromDate=$1 
toDate=$2 
oldDate=`date --date="3 years ago" +%Y-%m-%d` 
echo "Two Yrs Back Date ==> $oldDate" 
if [ $toDate -le $oldDate ] 
then 
find . -type f -newermt $fromDate ! -newermt $toDate -exec truncate -s 0 {} \; && echo "truncated" 
else 
echo "todate should be less than three years" 
fi 
echo "Done" 

得到的錯誤 - line 15: syntax error: unexpected end of file 雖然行15是不存在的腳本只有14行。此外,bash腳本運行良好,直到命令echo "Two Yrs Back Date ==> $oldDate"。 之後它會在if條件開始時給出錯誤。 只是想檢查我正在做的任何語法錯誤。

+1

引用所有的變數。 – 123

+0

bash腳本運行良好,直到命令'echo「Two Yrs Back Date ==> $ oldDate」'之後,它在if條件開始時給出錯誤。 – Sam

+0

'bash -n yourscpript'說什麼?當你做'od -c yourscript'時,任何有趣的角色(\ r而不是\ n)? – Jens

回答

-1

運算符-le用於比較整數,而不是用於字符串。

嘗試

if [[ "$toDate" < "$oldDate" ]] 

嚴格低於或

if [[ "$toDate" < "$oldDate" ]] || [[ "$toDate" = "$oldDate" ]] 

少-或相等。

(見http://www.tldp.org/LDP/abs/html/comparison-ops.html

+0

這不能解決語法錯誤。另外,POSIX並沒有將'<'指定爲'['的運算符,所以您最好使用'[[$ toDate <$ oldDate]]',因爲您已經依賴'bash'實現<'。另外,'-o'被認爲是過時的;你應該使用兩個用'||'連接的命令:'[...] || [...]'。 – chepner

0

使用此:

#!/bin/bash 

echo "Process Started" 
Current_Date=$(date +%Y-%m-%d) 
echo "todays Date ==> $Current_Date" 

fromDate=$1 
toDate=$2 
oldDate=$(date --date="3 years ago" +%Y-%m-%d) 
echo "Two Yrs Back Date ==> $oldDate" 

if [[ "$toDate" < "$oldDate" ]] || [[ "$toDate" = "$oldDate" ]]; then 
    find . -type f -newermt "$fromDate" ! -newermt "$toDate" -exec truncate -s 0 {} \; && echo "truncated" 
else 
    echo "todate should be less than three years" 
fi 
echo "Done" 

您可以用條件結構[[]]比較lexicographically。爲了比較在bash的約會,你需要使用:

[[ expression ]] 
Return a status of 0 or 1 depending on the evaluation of the conditional expression expression

whoan答案抽取。this post

是乾淨的使用shellcheck工具警告。別忘了引用這些變量來避免問題! shellcheck正顯示出這樣的事情:^-- SC2053: Quote the rhs of = in [[ ]] to prevent glob matching

1

你有相當多的需要行情展開的:

if [ "$toDate" -le "$oldDate" ] 

find . -type f -newermt "$fromDate" ! -newermt "$toDate" 

沒有看到你如何調用腳本,這是很難知道是否這些都有助於你的問題,但無論如何它們應該是固定的。

您可能會發現它有助於保持一致,並引用變量賦值,太:

fromDate="$1" 
toDate="$2" 

你的腳本還未能在第9行,作爲-le需要一個整數 - 你可能意味着給date格式字符串(如+%s)以獲得可比較的整數。

另外,請不要在您的示例代碼中放置破壞性命令,例如truncate - 它應該足以僅用於echo或其他。

+0

作業不需要被引用,儘管它並沒有受到傷害,當然。 –

+1

謝謝@BenjaminW - 我一直引用我的意見,並沒有意識到它不是必需的。答案已更新。 –

相關問題