Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

batch script if user press Ctrl+C do a command before exiting

I wrote a script which is doing net use at the beginning and net use /DELETE at the end.

But if user decides to press Ctrl + C and exits the script, I need to do a net use /DELETE.

Is that possible? I can't find anything on google.

like image 660
Nico Avatar asked Nov 25 '14 15:11

Nico


People also ask

How Use Ctrl C in batch file?

(1) (ConTRoL-C) In a Windows PC, holding down the Ctrl key and pressing the C key copies the currently highlighted object. The Mac equivalent is Command-C. See Ctrl-V. (2) (ConTRoL-C) In a Windows PC, holding down the Ctrl key and pressing the C key cancels the running program or batch file.

How do you wait for a batch command to finish?

Use the timeout command to specify the delay time in seconds. By inserting the timeout command into your batch file, you can prompt the batch file to wait a specified number of seconds (or for a key press) before proceeding. This command is available on all modern versions of windows, including Windows 10.

How do I send CTRL C signal?

Sending Signals Using The Keyboard Ctrl-C. Pressing this key causes the system to send an INT signal ( SIGINT ) to the running process. By default, this signal causes the process to immediately terminate.

What keys should you press to abort a batch file while running?

Ctrl+C. One of the most universal methods of aborting a batch file, command, or another program while it's running is to press and hold Ctrl + C . This keyboard shortcut sends a SIGINT signal, which cancels or terminates the currently-running program and returns you to the command line.


1 Answers

Sure, simply execute most of your script in a new CMD session:

@echo off
if "%~1" neq "_start_" (
  net use ...
  cmd /c "%~f0" _start_ %*
  net use /delete ...
  exit /b
)
shift /1
REM rest of script goes here

As long as your console window remains open, the net use /delete command will always fire after the inner cmd session closes. It could close because of normal run, user presses Ctrl-C, or fatal error - the final net use \delete will still fire.

like image 141
dbenham Avatar answered Nov 04 '22 09:11

dbenham