MS-DOS 如何将命令输出作为变量

MS-DOS how to get output of command as variable

我写了一个程序,returns 键码作为 DOS 的整数 但我不知道如何将它的输出作为变量。

注意:我使用的是 MS-DOS 7 / Windows 98,所以我不能使用 FOR /FSET /P

有人知道我该怎么做吗?

Eric Pement here 描述了一些解决方案。但是,对于旧版本的 cmd,作者被迫使用外部工具。

例如,Douglas Boling 的 STRINGS 等程序工具允许使用以下代码:

echo Greetings! | STRINGS hi=ASK # puts "Greetings!" into %hi%

Richard Breuer 的 ASET 也是如此:

echo Greetings! | ASET hi=line # puts "Greetings!" into %hi%

另一种纯 DOS 解决方案需要将程序输出重定向到文件(在下面的示例中命名为 ANSWER.DAT),然后使用专门准备的批处理文件。引用上述页面:

[I]n the batch file we need to be able to issue the command set MYVAR={the contents of ANSWER.DAT go here}. This is a difficult task, since MS-DOS doesn't offer an easy way to prepend "set MYVAR=" to a file [...]

Normal DOS text files and batch files end all lines with two consecutive bytes: a carriage return (Ctrl-M, hex 0D, or ASCII 13) and a linefeed (Ctrl-J, hex 0A or ASCII 10). In the batch file, you must be able to embed a Ctrl-J in the middle of a line.

Many text editors have a way to do this: via a Ctrl-P followed by Ctrl-J (DOS EDIT with Win95/98, VDE), via a Ctrl-Q prefix (Emacs, PFE), via direct entry with ALT and the numeric keypad (QEdit, Multi-Edit), or via a designated function key (Boxer). Other editors absolutely will not support this (Notepad, Editpad, EDIT from MS-DOS 6.22 or earlier; VIM can insert a linefeed only in binary mode, but not in its normal text mode).

If you can do it, your batch file might look like this:

@echo off
:: assume that the datafile exists already in ANSWER.DAT
echo set myvar=^J | find "set" >PREFIX.DAT
copy PREFIX.DAT+ANSWER.DAT  VARIAB.BAT
call VARIAB.BAT
echo Success! The value of myvar is: [%myvar%].
:: erase temp files ...
for %%f in (PREFIX.DAT ANSWER.DAT VARIAB.BAT) do del %%f >NUL

Where you see the ^J on line 3 above, the linefeed should be embedded at that point. Your editor may display it as a square box with an embedded circle.