LinuxQuestions.org
Go Job Hunting at the LQ Job Marketplace
Go Back   LinuxQuestions.org > Blogs > catkin
User Name
Password

Notices

Rate this Entry

Getting a timestamp string in a Windows cmd.exe variable

Posted 12-12-2010 at 01:31 PM by catkin

This technique was developed to generate a timestamp string for rsync's --backup-dir option but it could be generally useful.

The first issue is that the value of %DATE% depends on Windows' regional settings so is not portable. The same goes for the output format of cmd.exe's builtin command date. (one example of many discussions: this StackOverflow thread). There is no way to program around this in a .BAT or .CMD script. The chosen solution was to UnxUtils' date.exe which is a pure Windows implementation (no Cygwin or such like required) of the *n*x date command. With UnxUtils' date.exe copied to C:\WINDOWS\system32\UnxUtilsDate.exe, it is possible to portably generate a timestamp at the command prompt:
Code:
UnxUtilsDate.exe +%Y-%m-%d@%H:%M
2010-12-12@22:31
The next issue was how to get the timestamp into a cmd.exe variable. cmd.exe only implements "command substitution" in the for loop (example: post 13 in this Computing.net thread). The syntax is:
Code:
FOR /F ["options"] %variable IN (`command`) DO command [command-parameters]
After experimentation (the %variable seems to have to have a single letter name):
Code:
FOR /F "usebackq" %t IN (`UnxUtilsDate.exe +%Y-%m-%d@%H:%M`) DO SET TIMESTAMP=%t
All the % characters must be doubled when this is used in a .cmd file, including those in the format string, leading to this illustrative scrippet including using the timestamp in an rsync command:
Code:
REM Get timestamp for --backup-dir the Windows command substitution way
FOR /F "usebackq" %%t IN (`UnxUtilsDate.exe +%%Y-%%m-%%d@%%H:%%M`) DO SET TIMESTAMP=%%t

rsync --backup --backup-dir %TIMESTAMP% --compress --password-file password.txt --prune-empty-dirs --recursive --relative --times /cygdrive/c/WINDOWS/system32/drivers/etc/ CW8vWXP@10.0.2.2::CW8vWXP/
Best

Charles
Posted in Uncategorized
Views 3761 Comments 0
« Prev     Main     Next »
Total Comments 0

Comments

 

  



All times are GMT -5. The time now is 02:35 PM.

Main Menu
Advertisement

My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration