Download your favorite Linux distribution at LQ ISO.
Go Back > Blogs > catkin
User Name


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:
UnxUtilsDate.exe +%Y-%m-%d@%H:%M
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 thread). The syntax is:
FOR /F ["options"] %variable IN (`command`) DO command [command-parameters]
After experimentation (the %variable seems to have to have a single letter name):
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:
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@

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




All times are GMT -5. The time now is 10:43 AM.

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