【问题标题】:Why is my bash script creating files without telling it to?为什么我的 bash 脚本在不告诉它的情况下创建文件?
【发布时间】:2015-12-14 18:17:15
【问题描述】:

我正在运行以下脚本,该脚本的功能旨在告诉我一个日期是否早于另一个日期,如脚本的最底部所示。

现在,脚本有一些错误。但其中一个特别奇怪。该脚本创建由最后一个参数输入的日期命名的文件。

它会创建名为“09”、“12”和“2015”的文件。为什么要创建这些文件?这是功能。你会注意到最后几行使用输入调用函数

function compare_two {
if [ $1 < $2 ];
then
        return 2
elif [ $1 > $2 ];
then
        return 3
else
        return 4
fi
}


function compare_dates {
# two input arguments:
# e.g.  2015-09-17 2011-9-18

date1=$1
date2=$2

IFS="-"


test=( $date1 )
Y1=${test[0]}
M1=${test[1]}
D1=${test[2]}

test=( $date2 )
Y2=${test[0]}
M2=${test[1]}
D2=${test[2]}

compare_two $Y1 $Y2
if [ $? == 2 ];
then
        echo "returning 2"
        return 2
elif [ $? == 3 ];
then
        return 3
else
        compare_two $M1 $M2;
        if [ $? == 2 ];
        then
                echo "returning 2"
                return 2
        elif [ $? == 3 ];
        then
                return 3
        else
                compare_two $D1 $D2;
                if [ $? == 2 ];
                then
                        echo $?
                        echo "return 2"
                        return 2
                elif [ $? == 3 ];
                then
                        echo "returning 3"
                        return 3
                else
                        return 4
                fi
        fi
fi
}

compare_dates 2015-09-17 2015-09-12
echo $?

结果不会抛出错误,而是输出

returning 2
2

结果不正确,我知道。但我稍后会解决这个问题。是什么创建了这些文件,我该如何停止它?谢谢。

【问题讨论】:

  • 因为&gt; 不是您认为的运算符。它不是[ 中的大于运算符。它是输出重定向。你想要-gt[[ $1 &gt; $2 ]]
  • shellcheck.net 是你的朋友。
  • [ 确实将 &gt; 作为字符串比较运算符,但您必须对其进行转义,以便 [ 实际上将其作为参数接收。

标签: bash file shell scripting osx-yosemite


【解决方案1】:

较低和较大的符号被解释为重定向。 输入 man test 并找出正确的语法

【讨论】:

    【解决方案2】:

    您的问题在于[ $1 &lt; $2 ]&lt; 被理解为重定向字符。

    解决方案是使用以下任何一种替代方法:

    [ $1 \< $2 ]
    [ $1 -lt $2 ]
    (( $1 < $2 ))                     # works in bash.
    

    [[ $1

    « 运算符使用当前语言环境按字典顺序排序 »

    我建议使用(( $1 &lt; $2 )) 选项。

    为避免某些数字(以零开头的数字)如 08 在算术展开式中进行比较时会导致问题,请使用:

    (( 10#$1 < 10#$2 ))
    (( 10#$1 > 10#$2 ))
    

    强制以 10 为基数。

    但是,如果可能的话,恕我直言,使用 GNU 日期要容易得多(它将年/月/日转换为一个数字进行比较:自纪元以来的秒数):

    a=$(date -d '2015-09-17' '+%s');
    b=$(date -d '2015-09-12' '+%s');
    compare_two "$a"  "$b" 
    

    【讨论】:

      猜你喜欢
      • 2016-08-04
      • 2020-03-22
      • 1970-01-01
      • 2011-08-07
      • 2018-04-25
      • 2019-09-27
      • 1970-01-01
      • 2020-02-16
      • 2016-03-09
      相关资源
      最近更新 更多