【问题标题】:How can I write a shell scripts that calls another script for each day starting from start date upto current date [duplicate]如何编写一个 shell 脚本,从开始日期到当前日期每天调用另一个脚本 [重复]
【发布时间】:2021-11-14 11:39:24
【问题描述】:

如何编写一个每天调用另一个脚本的 shell 脚本

即目前有

#!/bin/sh
./update.sh 2020 02 01
./update.sh 2020 02 02
./update.sh 2020 02 03

但我只想指定开始日期 (2020 02 01) 并让 update.sh 每天运行直到当前日期,但不知道如何在 shell 脚本中操作日期。

我尝试了一下,但比较乱,如果它可以自己处理日期,我会更喜欢。

#!/bin/bash
    for j in {4..9}
    do
       for k in {1..9}
       do
          echo "update.sh" 2020 0$j 0$k
          ./update.sh 2020 0$j 0$k
       done
    done

    for j in {10..12}
    do
       for k in {10..31}
       do
          echo "update.sh" 2020 $j $k
          ./update.sh 2020 $j $k
       done
    done

    for j in {1..9}
    do
       for k in {1..9}
       do
          echo "update.sh" 2021 0$j 0$k
          ./update.sh 2021 0$j 0$k
       done
    done

    for j in {1..9}
    do
       for k in {10..31}
       do
          echo "update.sh" 2021 0$j $k
          ./update.sh 2021 0$j $k
       done
    done

【问题讨论】:

    标签: unix sh


    【解决方案1】:

    您可以使用date 将输入的日期转换为秒数以便进行比较。也可以使用date 添加一天。

    #!/bin/bash
    start_date=$(date -I -d "$1")   # Input in format yyyy-mm-dd
    end_date=$(date -I)             # Today in format yyyy-mm-dd
    
    echo "Start: $start_date"
    echo "Today: $end_date"
    
    d=$start_date                    # In case you want start_date for later?
    end_d=$(date -d "$end_date" +%s) # End date in seconds
    
    while [ $(date -d "$d" +%s) -le $end_d ]; do # Check dates in seconds
        # Replace `echo` in the below with your command/script
        echo ${d//-/ }               # Output the date but replace - with [space]
        d=$(date -I -d "$d + 1 day") # Next day
    done
    

    在本例中,我使用echo,但将其替换为您的update.sh 的路径。 示例输出:

    [user@server:~]$ ./dateloop.sh 2021-08-29
    Start: 2021-08-29
    End  : 2021-09-20
    2021 08 29
    2021 08 30
    2021 08 31
    2021 09 01
    2021 09 02
    2021 09 03
    2021 09 04
    2021 09 05
    2021 09 06
    2021 09 07
    2021 09 08
    2021 09 09
    2021 09 10
    2021 09 11
    2021 09 12
    2021 09 13
    2021 09 14
    2021 09 15
    2021 09 16
    2021 09 17
    2021 09 18
    2021 09 19
    2021 09 20
    

    【讨论】:

      猜你喜欢
      • 2015-08-23
      • 2012-01-11
      • 2023-04-09
      • 1970-01-01
      • 2020-12-23
      • 2015-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多