1

Going nuts with escaping! Trying to apply the "trick"

for /f "delims=" %%a in ('command') do @set theValue=%%a

(found at Set the value of a variable with the result of a command in a Windows batch file) to assign the result of a command to an environment variable.

But when the command needs to contain single quotes - in my example: date '+%s' (to obtain the time in seconds) - how can I escape the single quotes inside a single quoted string?

I tried with doubling them '' and prefixing with \ but neither worked. Also using double quotes around command (i.e. "date '+%s'") did not work... :-(

mmo
  • 3,897
  • 11
  • 42
  • 63
  • 2
    see `for /?`, especially `usebackq`. (Btw: batch's general way of escaping is a caret `^`. The backslash is just an ordinary character. Doubling only works for `%` and sometimes for `"`) – Stephan Nov 20 '19 at 09:31
  • 2
    `date '+%s'` will not work, independent of quoting. You are mixing bash and batch. You should test commands on the command line, before embedding them in a FOR-loop – jeb Nov 20 '19 at 09:36
  • `for /F` seems to take the outer pair of `'`, so no escaping is necessary: `for /F "usebackq" %%I in ('some'test'text') do @echo %I` returns `some'test'text`... – aschipfl Nov 20 '19 at 09:42
  • @Stephan: thanks for providing the correct esc,character! – mmo Nov 20 '19 at 12:30
  • @jeb: you are right. I have cygwin installed, that's why this accidentally worked. Will need to find a different solution. – mmo Nov 20 '19 at 12:30
  • @aschpfl: Unfortunately that did not work for me. – mmo Nov 20 '19 at 12:31

2 Answers2

0

The problem in your case, the date command isn't the one you expected.
When using cygwin's date command you need to use the full path to the specific exe file.

And as you are in batch you need to double the percent signs.
If you enclose +%s itself inside ticks isn't important.

@echo off

set "cygdate=c:\cygwin64\bin\date.exe"
for /F %%X in ('%cygdate% '+%%s'') do echo ## %%X
jeb
  • 78,592
  • 17
  • 171
  • 225
0

It appears that the goal is to get a "UNIX time", seconds since epoch. If so, and you are on a supported Windows system, it will have PowerShell.

The only hack needed to get this PowerShell command to run in a cmd.exe statement is to double the percent % character in '%%s'.

FOR /F "usebackq" %%A IN (`powershell -NoLogo -NoProfile -Command ^
    "[Math]::Floor([decimal](Get-Date(Get-Date).ToUniversalTime() -uformat '%%s'))"`) DO (
    SET "theValue=%%A"
)
ECHO %theValue%

Adapted from https://stackoverflow.com/a/25916431/447901

lit
  • 14,456
  • 10
  • 65
  • 119