Tutorial: Batch Script Tutorial
- string comparison in IF is by default case sensitive. To make it case insensitive, use the
/iswitch. (source) - if the last line of your code before a closing parentheses is a
::comment, like this:
then you'll get this error:@echo off IF 1==1 ( echo 1 echo 2 ::echo 3 )
) was unexpected at this time. - if the script stops after executing a command to a command line tool (i.e.
npm install), you're probably calling it withoutCALL. You should call it withCALL(i.e.CALL npm install). (source) - hidden files and folders do not get detected with
FOR %%a in (*)or inFOR /D %%a in (*). Here's how to query for hidden fires/folders. - Use
@echo offto avoid printing every executed line. - if you do a
SETLOCALmake sure to useENDLOCALat the end - variables (source):
SET foo=1--> set environmental variable
%foo%--> refer to environmental variable!foo!--> refer to environmental variable with delayed expansion%%a--> FOR loop variable referred to in batch script
%a--> FOR loop variable referred to in command line- variable declaration and spaces and quotes -- pay attention to these.
- delayed expansion: (source and example) --> use it if you need to create and modify variables within loops.
@echo off setlocal enabledelayedexpansion set searchfor=a c for %%a in (a b c d) do ( set item="%%a" set found=0 ( for %%b in (%searchfor%) do ( set candidate="%%b" if "!item!"=="!candidate!" ( set found=1 ) ) ) if "!found!"=="0" ( echo "!item!" did not match any of the search terms ) else ( echo "!item!" was a match ) ) endlocal - functions
- documentation: read here.
- maximum length of a label is not 8 characters anymore
- execution order: (source)
it is very important to do the navigation with goto :eof and goto :end. If these navigations are left out it can cause code segments to run multiple times
@echo off call :foo call :foo2 goto end :foo echo foo goto :eof :foo2 echo foo2 goto :eof :end echo done - processing input arguments (source for foo; source for foo2)
@echo off call :foo 1 2 3 call :foo2 a b c goto end :foo for %%a in (%*) do ( echo %%a ) goto :eof :foo2 echo %~1 echo %~2 echo %~3 goto :eof :end
No comments:
Post a Comment