Matěj Maty Macura
Matěj Maty Macura

Reputation: 15

Batch-I want to set second part of variable

I have a problem.

set /p command=  
if %command% == "display (i want the second part of the variable here)" echo (second part of the variable)

For example, i type:

display hello 

I want it to simply:

echo hello

I want to use this for custom commands in my game.

Upvotes: 1

Views: 48

Answers (1)

rojo
rojo

Reputation: 24466

Firstly, you can split the text on firstword|notfirstword with a for /f loop using "tokens=1*". See help for in a console window for full details.

Next, you could use attempt to call :label where :label is whatever the first word was. In essence, you're creating batch functions and letting the user choose which function is executed. If the function label doesn't exist, then errorlevel will be non-zero and you can handle appropriately using conditional execution. This makes it easy to expand your script without having to add an if /i statement for each choice or synonym you add. (It might be a good idea to hide the error message for attempting to call a non-existent label by redirecting 2>NUL.) Here's a full example:

@echo off & setlocal

:entry
set /P "command=Command? "

for /f "tokens=1*" %%I in ("%command%") do (
    2>NUL call :%%I %%J || (
        if errorlevel 1000 (exit /b 0) else call :unsupported %%I
    )
    goto :entry
)

:display
:echo
:say
:show
echo(%*
exit /b 0

:ping
ping %~1
exit /b 0

:exit
:quit
:bye
:die
echo OK, toodles.
exit /b 1000

:unsupported <command>
1>&2 echo %~1: unrecognized command
exit /b 0

Upvotes: 2

Related Questions