Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

328
Visualizações
Bash validate date

I'm writing a shell script and am confused as to why my date validation code is not working. I tried the following solutions to similar questions I found, but is_valid is always set to 1:

date "+%m/%d/%Y" -d "$1" 2>1 > /dev/null
//or..
date -d "2012-02-29" > /dev/null 2>&1
is_valid=$?
#always set to 1, even when given a valid date

How do I correctly validate the date format? The date should only be valid if in the format MM/DD/YYYY

I also tried this solution: Linux Bash - Date Format but it always rejected the date as well.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

The BSD date that ships with Mac OS X doesn't support the -d option (or rather, it uses -d for something entirely different). Either install GNU date, or use the following to validate your input string:

date -f "%Y-%m-%d" -j "2012-02-29" >/dev/null 2>&1

The -f provides the input format, and the -j tells date to simply output the date, not attempt to set the system clock.

over 4 years ago · Santiago Trujillo Relatório

0

I came up with this little function:

function isDateInvalid()
{
  date -d "$1" "+%m/%d/%Y" > /dev/null 2>&1
  res=$?
  echo "$res"
}

isDateInvalid "2012-02-219"
1

isDateInvalid "2012-02-29"
0
over 4 years ago · Santiago Trujillo Relatório

0

for y in {2013..2014}; do
  for m in {01..12}; do
    for d in {01..31}; do
      [[ ! "`date -jf %Y%m%d $y$m$d +%Y%m%d`" = "$y$m$d" ]] && continue
      echo $y.$m.$d
    done
  done
done

if strings match, loop will proceed ...

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda