批处理文件
批处理文件 - 检查命令是否可用(Batch file - check if command is available)我正在Windows中编写一个小批量文件,需要运行nodejs应用程序。 在运行应用程序之前,我需要确保用户安装了该节点,如果没有向他显示该节点是必需的消息。
我做的是这样的:
@echo OFFsetlocal EnableDelayedExpansionREM Check if node is installedfor /f "delims=" %%i in ('node -v') do set output=%%iIF "!output!" EQU "" ( echo node could not be found) else ( node %~dp0app.js)如果用户已安装节点,则output将包含版本号。 如果没有安装,那么它将是空的。 这个逻辑有效。 但是,如果未安装node -v (未找到node -v命令),则批处理结果还会显示以下输出:
'node' is not recognized as an internal or external command,operable program or batch file.node could not be found我想隐藏用户的“未识别”消息,只显示“无法找到节点”。
我怎么能隐藏它?
I'm writing a small batch file in windows that needs to run a nodejs app. Before running the app I need to make sure that node is installed by the user, and if not show him a message that node is required.
What I did is this:
@echo OFFsetlocal EnableDelayedExpansionREM Check if node is installedfor /f "delims=" %%i in ('node -v') do set output=%%iIF "!output!" EQU "" ( echo node could not be found) else ( node %~dp0app.js)If the user has node installed then output will contain the version number. If not installed then it will be empty. This logic works. But if node is not installed (node -v command not found), the batch result also shows the following output:
'node' is not recognized as an internal or external command,operable program or batch file.node could not be foundI would like to hide the "not recognized" message from the user and just show "node could not be found".
How can I hide it?
最满意答案抑制错误消息,将其重定向到NUL:
set "output=not installed"for /f "delims=" %%i in ('node -v 2^>nul') do set output=%%iecho %output%另一种方式(灵感来自Npocmaka的答案):
where node.exe >nul 2>&1 && echo installed || echo not installed或者更接近原始输出:
where node.exe >nul 2>&1 && node %~dp0app.js || echo node could not be foundto suppress the errormessage, redirect it to NUL:
set "output=not installed"for /f "delims=" %%i in ('node -v 2^>nul') do set output=%%iecho %output%another way (inspired by Npocmaka's answer):
where node.exe >nul 2>&1 && echo installed || echo not installedor to keep closer to your original output:
where node.exe >nul 2>&1 && node %~dp0app.js || echo node could not be found