我正在制作一个需要运行用户输入的命令的程序。 如果该命令不存在,则会打开错误。
:cmd
set /p cmd="Command:"
if not exist %cmd% goto nocommand
%cmd%
:noCommand
echo Error, command doesn't exist..
goto cmd
但如果我输入#34; echo text"它说文字不是一个命令。我需要它只读第一个单词。
答案 0 :(得分:1)
检查是否可以从给定路径或%PATH%执行命令作为内部命令。它还使用了来自dbenham的解决方案:Check if command is internal in CMD
@echo off
:cmd
set /p "cmd=Command:"
for /f "tokens=1 delims= " %%a in ("%cmd%") do set "fcmd=%%~na"
setlocal
set "empty=%temp%\empty%random%"
md "%empty%"
pushd "%empty%"
set path=
>nul 2>nul %fcmd% /?
if not errorlevel 9009 (
popd
rd "%empty%"
echo %fcmd% is internal command
endlocal
goto :execute
) else (
popd
rd "%empty%"
endlocal
)
color
for %%# in (%PATHEXT%;"" ) do (
rem echo --%fcmd%%%~#--
if exist %fcmd%%%~# (
echo the command/executable/script will be executed from given location
goto :execute
)
for /f "tokens=1 delims= " %%a in ("%fcmd%%%~#") do (
if "%%~$PATH:a" NEQ "" (
echo the command/executable/script is defined in %%PATH%%
rem
goto :execute
)
)
)
echo command does not exist
exit /b 1
:execute
%cmd%
答案 1 :(得分:0)
set /p cmd="Command:"
for /f "tokens=1" %%i in ("%cmd%") do set firstword=%%i
echo %firstword%