Сохраните все даты в данном диапазоне дат в переменную

Существует ли причина, почему Вы хотели бы использовать загрузчик Windows конкретно? При установке личинки или syslinux на диске SATA можно создать menuentry для Windows, а также систем Linux - на самом деле, другие загрузчики ОС, в большинстве случаев, автоматически обнаружены и настроены. Иначе, если Вы все еще предпочитаете придерживаться загрузчика Windows, Вы могли бы хотеть искать решение на их веб-сайтах... что-то как MSDN.

6
07.07.2014, 16:02
2 ответа

Я бы выбрал совершенно другой подход. Все вычисления даты вручную подвержены ошибкам (не всегда 31 день в месяце, у вас високосные годы и т.д.). Кроме того, пролистывая свой код, очень сложно сказать, что вы делаете (что очень плохо).

#!/bin/bash
startdate=20141030
enddate=20141120

dates=()
for (( date="$startdate"; date != enddate; )); do
    dates+=( "$date" )
    date="$(date --date="$date + 1 days" +'%Y%m%d')"
done
echo "${dates[@]}"

Для этого используется команда date, которая обрабатывает все вычисления, сохраняя каждую дату в массиве $dates.

Результат выглядит следующим образом:

20141030 20141031 20141101 20141102 20141103 20141104 20141105 20141106 20141107 20141108 20141109 20141110 20141111 20141112 20141113 20141114 20141115 20141116 20141117 20141118 20141119
12
27.01.2020, 20:22

Если, как вы объясняли в своих комментариях, ваша конечная цель здесь - найти все файлы, измененные в заданном диапазоне дат, то сохранение указанного диапазона в переменную бессмысленно. Вместо этого вы можете дать диапазон найти напрямую:

find . -mtime $start -mtime $end

Лично я бы использовал другой подход. Просто создайте два временных файла, один создал второй до даты начала и один создал второй после даты окончания. Затем воспользуйтесь тестом GNU find -newer, чтобы найти файлы, которые новее первого и не новее последнего.

Коварный бит получает $start и $end правильно. Вы можете попробовать что-нибудь вроде:

#!/usr/bin/env bash

## If you really want to use this format, 
## then you must be consistent and always 
## us YYYYMMDD and HHMMSS.
startdate=20141030
starttime=165800

enddate=20141120
endtime=175050

## Get the start and end times in a format that GNU date can understand
startdate="$startdate $( sed -r 's/(..)(..)(..)/\1:\2:\3/' <<<$starttime)"
enddate="$enddate $( sed -r 's/(..)(..)(..)/\1:\2:\3/' <<<$endtime)"

## GNU find has the -newer test which lets you find files
## that are newer than the target file. We can use this
## and create two temporary files with the right dates.
tmp_start=$(mktemp)
tmp_end=$(mktemp)

## Now we need a date that is one seond before the
## start date and one second after the end date.
## We can then use touch and date to set the creation date 
## of the temp files to these dates. 
minusone=$(date -d "$startdate -1 sec" +%s)
plusone=$(date -d "$enddate +1 sec" +%s)

## Set the creation times of the temp files.
## The @ is needed when using seconds since
## the epoch as a date string.
touch -d "@$minusone" $tmp_start
touch -d "@$plusone" $tmp_end

## At this point we have two files, tmp_start and
## tmp_end with a creation date of $startdate-1 
## and $enddate+1 respectively. We can now search
## for files that are newer than one and not newer
## than the other.
find . -newer $tmp_start -not -newer $tmp_end

## Remove the temp files
rm $tmp_start $tmp_end
3
27.01.2020, 20:22

Теги

Похожие вопросы