• 发生时间:2022-05-06

  • 问题描述:

    • 我在上位机打包批处理脚本中增加一行 yarn dist 命令(如下所示),运行脚本时发现: 当脚本运行 yarn dist 成功后就退出了,没有运行后面的命令。
    REM ...
    echo "pack electron ..."
    REM I add a command `yarn dist`, which will call `electron-builder`.
    yarn dist
    REM The script will exit here, and the following commands will never be run.
    xcopy /e/y .\dist\win-unpacked .\app\
    REM ...
    
  • 问题类别:软件开发

  • 原因分析:

    1. 在网上简单搜索后,发现 npm 的 github issue #2938 中也提到这个问题,里面给出了一个复现这个问题的代码片段:
    echo before
    REM The script will exit after running the following command.
    npm --version
    REM The following echo command will never be run.
    echo after
    
    1. 结合 stack overflow 的两个网页(网页1网页2)找到这个问题的原因和解决方案。 原因是 Windows 系统下的 npm 或 yarn 命令都是 bat 脚本,而 windows bat 在调用下一个 bat 脚本前会退出当前 bat 脚本。 如果不想提前退出,需要在调用的脚本前增加 call 关键字

    When not using CALL, the current batch file stops and the called batch file starts executing. It’s a peculiar behavior dating back to the early MS-DOS days.

  • 解决方案:将 yarn dist 修改为 call yarn dist

  • 实施结果:修改后脚本可以正常运行。

  • 经验总结:

    1. 在 Windows bat 脚本中调用其他 bat 脚本时,需要在前面加上 call,否则脚本会提前退出。
    2. 经测试,在 Windows bat 脚本中直接调用 exe 程序时,脚本不会提前退出,因此此时不需在前面加上 call
    3. 但我们往往难以区分一个命令是 exe 还是 bat 脚本,此时只能通过实际测试来确认是否需要加上 call
    4. 个人觉得 Windows bat 语法很不友好、比较难用(比 Linux bash 还难用),因此非必要尽量不要写 Windows bat 脚本。

参考资料

  1. Executing npm from DOS batch file terminates the script
  2. prevent “abort” in windows batch for npm install
  3. How to run multiple .BAT files within a .BAT file
  4. windows commands: call