Introduction: Super Advanced Batch Coding
This is the fourth batch tutorial I am releasing see tutorial one here
And tutorial two here
Here is tutorial three
In this tutorial I will review more if statements getting text with ~ and when to use ! not % for environmental variables.
Step 1: If Statemnts IV
If statemnts are some of the most useful things in batch codes but here is something else they can do.
Open cmd.exe and type color /? Or attrib +h nul.txt
Notice these commands have options /? For help and attrib allows for a file name if statements can let you do this
if /i "%~1"=="/?" (
Echo help section
This explained save it as help.bat open hold shift and right click in the same folder and open cmd type help /?
This code says if the first thing typed after the file name is /? Do what's in the parenthesis. Notice %~1 well what but the second thing I'm getting there.
if "%~2"=="" (
set /p var=Enter non-strict data
) else (
So you just change %~1 to %~2 yes, but what about the rest of the code?
Let's say you don't run it from cmd you open it like a batch file the second thing the user types into cmd is not valid so it prompts the user. But it looks different from code one why all those parenthesis? The first one required /? To go some where this allows for a file path to be typed which isn't the same text every time.
Step 2: When to Use ! Not %
So a wile ago I said to ALWAYS put environmental variables in between % signs but that's not always true.
When using the for or if command ( I haven't reviewed for because it's very advanced (I don't know how to use it))
@echo off &setlocal EnableDelayedExpansion
set /a "n = 0"
echo Before: %n%
echo In the loop:
for /l %%i in (1 1 3) do (
set /a "n += 1"
echo * Iteration #%%i:
echo percent signs: %n%
echo exclamation marks: !n!
echo After: %n%
Credit to aGerman via Dostips.com
In parenthesis and under setlocal ... when the variable changes
Step 3: Getting Text With ~
Set /p can be used for user input but let's say you don't want everything the user has to type here is what to do.
To get the last letter is ~-1
The last two is ~-2 and so on.
to exclude the first letter is ~1 and the second is ~2 and so on
to read the first letter only is ~0,1 and so on
But how do I use this?
Set /p var=Enter a word
IF "%var:~0,1%"=="a" (goto a) else (echo your word didn't start with the letter a && Goto top)
Echo yay your word starts with a
Step 4: Batch Challange
Using the batch skills you have post the coolest batch file you can make. Try to make it do something useful or display a cool effect or be a fun game!! I will review the winners script and comment on it. If you don't post in a few weeks I my not see the comment so I won't review it but you can still post it :)
I will also release tutorials on a specific batch command such as set if and for
See more of my batch codes here