luckyee
luckyee

Reputation: 167

About Print formated Datetime in linux shell scripts

After i type: date +"%y-%m-%d %H:%M:%S" in linux shell i get the right result such as: 14-09-26 10:47:28.

However, when i want to get the result in a shell script, I get a error : "date: illegal time format", Why?

#!/bin/sh

STR='date +"%y-%m-%d %H:%M:%S"'

echo "`$STR`"

Upvotes: 0

Views: 374

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753695

The trouble with:

#!/bin/sh

STR='date +"%y-%m-%d %H:%M:%S"'

echo "`$STR`"

is that when the string is executed in the echo command, the date command sees three arguments:

date
+%y-%m-%d
%H:%M:%S

It is trying to interpret the %H:%M:%S as a date/time in the format:

[[[mm]dd]HH]MM[[cc]yy][.ss]]

or:

mmddhhmm[[cc]yy]

or:

[MMDDhhmm[[CC]YY][.ss]]

(the first from Mac OS X date, the second from POSIX, the third from GNU date). In those, the pairs of letters represent components of the date to be set as the time. Since the %H:%M:%S string contains no digits, it is an invalid date format.

How could you work around this?

It depends in part on whether /bin/sh is Bash, Korn shell, Dash, Bourne shell or some other shell.

The simplest solution should work in all but the oldest Bourne shells, and that is to create a function:

dt() { date +'%Y-%m-%d %H:%M:%S'; }

You can then use:

echo "$(dt)"

using the $(…) notation in preference to back-ticks.

Note that I decline to use %y; I remember the Y2K bug, even if you're too young to have been involved in the remediation work.

An alternative technique requires support for arrays (Bash, Korn shells, but not Dash or Bourne):

STR=( date +"%Y-%m-%d %H:%M:%S" )

echo "$( "${STR[@]}" )"

or, more simply:

"${STR[@]}"

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26667

Try excecuting at the assignment iteself.

 $ #!/bin/sh

   $ STR=`date +"%y-%m-%d %H:%M:%S"`

   $ echo $STR
  14-09-26 11:40:06

Upvotes: 0

Related Questions