Wednesday, December 2, 2015

command line - How to "pause" only if executing in a new window?


I have authored a batch script that assumes %1 is a path to a file. At times I would like to use this batch script via drag-drop in Windows Explorer (dragging my target file onto my batch script file), and at other times I would like to run this batch script from an existing command prompt window and provide my %1 path explicitly (usually just a relative path).


I don't want my script to disappear immediately when "drag dropping", thus I need to pause. However, I don't want to have to press any key to continue every time when using an existing command prompt window, thus I don't want pause.


Is there a way to have the best of both worlds? Can I somehow detect/infer the scenario I'm in, and decide to pause or not pause thereafter? What's the best approach here?


Answer



Try using this in your batch file:


set arg0=%0
if [%arg0:~2,1%]==[:] pause

This checks whether the 3rd character of the 0th argument (basically, the batch file name itself) is a colon or not.


Normally, when you drag-and-drop something on a batch file, it's called as: "Drive:\path\to\Batch File.bat" Arg1 Arg2 ... However, when we execute a batch file from the Command Prompt we generally do not tend to call it like that, with a quoted absolute path. Thus we can exploit this difference and execute a pause only when the colon exists as the 3rd character, implying that the batch file was executed via drag-and-drop. Of course, if you do use a quoted absolute path to execute the batch file from the command prompt, it will naturally pause as well.


No comments:

Post a Comment

linux - How to SSH to ec2 instance in VPC private subnet via NAT server

I have created a VPC in aws with a public subnet and a private subnet. The private subnet does not have direct access to external network. S...