I hope I never have to write another Windows .BAT file again in my life, but if I don't jot this stuff down, I will forget it, and then I will.
- Use
:somelabel
to define a block of code. - Use
call :somelabel
to jump to a defined label, run that block of code to the end, then return. - Use
goto :label
to jump to that label. - Put
:eof
at the end of your file.
So,
if (some error) do (
echo nope, you messed up
goto :eof
)
for (whatever) do (
call :myprocess
)
goto :eof
:myprocess
echo do stuff here
:eof
for /f %%a in (a-file-with-one-thing-per-line.txt) do (
echo Here's the line: %%a
)
https://stackoverflow.com/questions/9252980/how-to-split-the-filename-from-a-full-path-in-batch
https://stackoverflow.com/questions/23735282/if-not-exist-command-in-batch-file
I used this to determine if a program was installed (I'm sure there's some better wiz-bang way to check the registry for it...)
:: Check if chrome is in the right place
if not exist "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" (
echo You don't have Chrome installed in "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe".
goto :eof
)
https://stackoverflow.com/questions/1291941/batch-files-number-of-command-line-arguments
There's not something like $#
in bash, so there's a whole level of hell involving looping and/or a bunch of GOTOs.
I wanted to check if there were no arguments; you can do this:
if "%1"=="" (
echo You need to pass at least one parameter, sorry.
goto :eof
)
rem change slashes to dashes in the first parameter passed
SET _test=%1
SET _result=%_result:/=-%
That second line is replacing one string with another, so you can do stuff like this, too:
SET _result=%_result:pepsi=coke%
For lots more of this https://www.dostips.com/DtTipsStringManipulation.php
Related: https://gist.github.com/jkonrath/fb471f4d15947555af254c877ca04d53
I covered this over here: https://gist.github.com/jkonrath/25188b7d8d59cd55b5843e0e557c06c6
I have no idea what I'm doing. I learned all of this by brute force. It worked for me, but it might not work for you, and it's probably not the best way of doing things.
Also I just realized I don't even have a machine to test these anymore, so caveat emptor.