3

I have date in this format: date -d $datum +"%Y-%m-%d" and on Linux it worked OK but in FreeBSD says this:

ERROR wrong format
usage: date [-jnRu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... 
            [-f fmt date | [[[[[cc]yy]mm]dd]HH]MM[.ss]] [+format]

what is response to this:

date -d $datum +"%Y-%m-%d" >/dev/null 2>&1 || echo "ERROR wrong format" 

But it prints out an error and then continues with the code and it seems that correctly. What am I supposed to do, so it wouldn't print out error and if there is error then the program exits?

1

2 Answers 2

2

I don't have a bsd box to test on, but it appears that you need to use this form:

date -f "some format" "$datum" "+%Y-%m-%d"

and you have to specify the format of the incoming datum so it can be parsed.

1
  • 1
    Shouldn't you also specify option -j to prevent date from attempting to set the system time? Mar 14, 2022 at 17:56
0

The GNU version of date that you're used to on Linux supports a lot more date format than the version of date on most other Unix variants. It also has many options that aren't present on other Unix variants. The only standard usage of date is to display the current date according to a format specified with a +… argument (and also a way for the system administrator to set the system date), and the -u option to specify UTC instead of the local timezone.

On FreeBSD, you can use the date utility to convert between date formats with the -f option, e.g. date -f %s "$datum" +%Y-%m-%d to convert a date expressed in seconds from the epoch to a human-readable format.

If you want fancy date parsing, you can install the coreutils package, which contains GNU date. Or you can use the Date::Parse module in Perl or dateutil in Python.


To make a shell script stop on most errors, add set -e just below the #! line.

If you want to display an error explicitly, it's up to you to then quit the script with an error status. Print errors to stderr, not to stdout.

date -d "$datum" +"%Y-%m-%d" >/dev/null 2>&1 || {
  echo "ERROR wrong format" >&2
  exit 1
}

or

if ! date -d "$datum" +"%Y-%m-%d" >/dev/null 2>&1; then
  echo "ERROR wrong format" >&2
  exit 1
fi
1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .