Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

My shell script:

#!/bin/bash
echo "$1";
startd=$(date -d "$1" +"%Y%m%d"); 
echo "$startd";

My command:

sudo ./test.sh "20151010"

The output:

20151010 
20150213

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

share|improve this question
    
Be warned: date -d with sudo might change system date in OSX –  Ketan Feb 13 at 23:12
    
I have no such problem with date under Linux. You may need to install the GNU Coreutils and use date from them. BTW, you do not need sudo. –  vinc17 Feb 13 at 23:15
1  
The OS X version of date doesn't parse arbitrary date formats like the GNU version does. –  Barmar Feb 13 at 23:23

2 Answers 2

up vote 2 down vote accepted

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:

#!/bin/bash
echo "$1";
startd=$(date -j -f '%Y%m%d' "$1" +'%Y%m%d'); 
echo "$startd";

Here's a transcript:

$ ./testdate.sh 20151010
20151010
20151010
share|improve this answer
    
it turns out developing these scripts on osx won't do for me than because production env is linux, And i want the linux version of scripts –  jaminator Feb 17 at 19:22

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.