adama
adama

Reputation: 557

open cmd from batch-script, run command and close the previously opened terminal

I made a small terminal menu where I can run several terminal commands in a new cmd.

Here a very compressed example:

    SET /P env=your conda env:    
    ...
    ECHO 2 - Run Rasa Action Server
    ...
    IF %M%==2 GOTO RUN_RASA_ACTION_SERVER
    ...
    :RUN_RASA_ACTION_SERVER
    start cmd.exe /k call conda activate %env% ^&^& cd.. ^&^& call rasa run actions
    CLS
    GOTO MENU

In this part I start an action server running on port 5055 in a new cmd terminal. I also want to kill the task via my terminal menu.

so here is what I got so far:

...
ECHO 6 - Kill Rasa Action Server
...
IF %M%==6 GOTO KILL_RASA_ACTION_SERVER
...
:KILL_RASA_ACTION_SERVER
FOR /F "tokens=5" %%T IN ('netstat -a -n -o ^| findstr "5055" ') DO (
SET /A ProcessId=%%T) &GOTO SkipLine



:SkipLine                                                                              
taskkill /f /pid %ProcessId%
CLS
GOTO MENU

This is working fine, BUT...the previously opened terminal is still open, I want to kill the task and close the cmd terminal after that.

How can I achieve this? I tried an EXIT but I always close the main terminal menu.

Upvotes: 0

Views: 314

Answers (1)

Ben Personick
Ben Personick

Reputation: 3264

The previously opened terminal is still open, I want to kill the task and close the cmd terminal after that.

Set a Window Title for the Shell Window you are opening

SET /P env=your conda env:    
 REM ...
ECHO 2 - Run Rasa Action Server
 REM ...
IF %M%==2 GOTO RUN_RASA_ACTION_SERVER
 REM ...
:RUN_RASA_ACTION_SERVER
start "KILL_ME_PLEASE" cmd.exe /k call conda activate %env% ^&^& cd.. ^&^& call rasa run actions
CLS
GOTO MENU

Then in your Other section you just find the CMD window with that title and kill it and any process it spawned.

 REM ...
ECHO 6 - Kill Rasa Action Server
 REM ...
IF %M%==6 GOTO KILL_RASA_ACTION_SERVER
 REM ...
:KILL_RASA_ACTION_SERVER
FOR /F "Tokens=2" %%_ IN ('
  TaskList -v /FI "ImageName eq cmd.exe" ^| FIND "KILL_ME_PLEASE"
') DO (
  TaskKill /T /F /PID %%_
)
CLS
GOTO MENU

Upvotes: 1

Related Questions