【问题标题】:How to write command to file in batch?如何将命令批量写入文件?
【发布时间】:2013-07-01 20:44:17
【问题描述】:

有没有办法将命令写入到文件中?

例如我的脚本是:

ping 127.0.0.1 >> file.txt

我想将ping 127.0.0.1 包含在我的file.txt 中,这样我就可以知道哪个命令产生了哪个输出。

当然我可以这样做:

echo "ping 127.0.0.1" >> file.txt
ping 127.0.0.1 >> file.txt

【问题讨论】:

    标签: batch-file


    【解决方案1】:

    调用批处理脚本时,留下echo on,输出整个脚本。

    命令行

    script.bat >> file.txt
    

    Script.bat

    @echo on
    ping "127.0.0.1"
    

    这也可以由脚本自行调用

    @echo off
    if /i not "%~1"=="self" call "%~f0" self >> file.txt & goto :EOF
    @echo on
    :: Everything (including commands) after this echo will be displayed in the file
    ping "127.0.0.1"
    

    【讨论】:

    • 你能解释一下@echo off之后的那一行吗?
    • if /i not "%~1"=="self" 这是检查脚本的第一个参数是否是单词“self”。我用它作为一个指示,看看脚本是否是自己启动的。 call "%~f0" self 正在使用 self 字参数开始新的脚本运行。 >> file.txt 正在将脚本的输出重定向到文本文件。 & goto :EOF 正在退出这个脚本实例,因为我们开始了一个新实例。此行使脚本可以捕获自身,而无需用户手动指定>> file.txt 输出捕获。
    【解决方案2】:

    怎么样

    @echo on
    

    在一个命令块之前,你要记录,然后一个

    @echo off
    

    之后呢?

    @echo off
    rem what i want to do
    rem some commands (setting variables etc.)
    @echo on
    ping 127.0.0.1" >> file.txt
    ipconfig /all >>file.txt
    @echo off
    rem some other commands (deleting temporary files etc) 
    

    【讨论】:

    • 不幸的是,这仍然只会捕获命令输出。命令本身只会显示在命令行上。必须捕获整个脚本才能在文件中包含命令。
    猜你喜欢
    • 2011-04-08
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    相关资源
    最近更新 更多