Convert input string to date in shell script

My shell script:

echo "$1";
startd=$(date -d "$1" +"%Y%m%d"); 
echo "$startd";

My command:

sudo ./ “20151010”

The output:


it printed todays date instead of printing the input date any idea?

Asked By: PUG


If you are trying to format date on OS X, you can try this:

date -j -f "%Y%m%d" "20151010"

I get the following output:

Sat Oct 10 17:27:28 CDT 2015
Answered By: Ketan Maheshwari

The OS X version of date uses the -f option to parse a formatted date/time:

date -j -f '%Y%m%d' "$1" +'%Y%m%d'

The -j option causes it to just print the time, not try to set the system clock. So the full script would be:

echo "$1";
startd=$(date -j -f '%Y%m%d' "$1" +'%Y%m%d'); 
echo "$startd";

Here’s a transcript:

$ ./ 20151010
Answered By: Barmar