2016-12-08 19 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 - 我一直引用我的意见,并没有意识到它不是必需的。答案已更新。 –

相关问题