Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I protect quotes in a batch file?

I want to wrap a Perl one-liner in a batch file. For a (trivial) example, in a Unix shell, I could quote up a command like this:

perl -e 'print localtime() . "\n"'

But DOS chokes on that with this helpful error message:

Can't find string terminator "'" anywhere before EOF at -e line 1.

What's the best way to do this within a .bat file?

like image 290
Jeff Youngstrom Avatar asked Sep 24 '08 23:09

Jeff Youngstrom


People also ask

How do I secure a batch file?

Unlike an executable file, a batch file can be opened in any text editor, making it easy to copy or modify. To protect the contents of your batch file, you must encrypt it using the native Windows 7 Encrypting File System.

What does %1 mean in a batch file?

When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.

How do you use quotation marks in CMD?

Generally, to differentiate commands from other types of instructions, enclose the command within single or double quotation marks. When issuing TSO/E commands in an exec, it is recommended that you enclose them in double quotation marks.


3 Answers

For Perl stuff on Windows, I try to use the generalized quoting as much as possible so I don't get leaning toothpick syndrome. I save the quotes for the stuff that DOS needs:

perl -e "print scalar localtime() . qq(\n)"

If you just need a newline at the end of the print, you can let the -l switch do that for you:

perl -le "print scalar localtime()"

For other cool things you can do with switches, see the perlrun documentation.

like image 141
brian d foy Avatar answered Oct 09 '22 19:10

brian d foy


In Windows' "DOS prompt" (cmd.exe) you need to use double quotes not single quotes. For inside the quoted Perl code, Perl gives you a lot of options. Three are:

perl -e "print localtime() . qq(\n)"
perl -e "print localtime() . $/"
perl -le "print ''.localtime()"

If you have Perl 5.10 or newer:

perl -E "say scalar localtime()"

Thanks to J.F. Sebastian's comment.

like image 35
tye Avatar answered Oct 09 '22 19:10

tye


For general batch files under Windows NT+, the ^ character escapes lots of things (<>|&), but for quotes, doubling them works wonders:

C:\>perl -e "print localtime() . ""\n"""
Thu Oct  2 09:17:32 2008
like image 31
Christopher G. Lewis Avatar answered Oct 09 '22 19:10

Christopher G. Lewis