Batch File Cheat Sheet



Help

Make sure that the Sample.html file and the selenium-server.jar. Visit Intellipaat for a comprehensive DevOps Training and be a certified DevOps Engineer! Download a Printable PDF of the Cheat Sheet. We have covered all the basics of Jenkins in this cheat sheet. With LSF you would view the file ADMINusage in your home directory. With Slurm you can run the command “hpcusage” to view your available and used resources. LSF to Slurm Batch Script Reference Note: Slurm submission scripts require a shell declaration as the first line. They will not run without this. Linux Command-Line Cheat Sheet. Operating Systems. Unix Tip: Use your Unix scripting skills to write a batch file. The solution was to whip up a batch file that mapped the drives.

help comman­dNamecomman­dName /?help --> show all system commands

All System Commands

help

Clear Screen

Clear Screencls

Shortcuts

TabAutoco­mpletearrow keys up/downback/f­orward history commandsControl + Cstops current commandALT + F7clears the historyF7shows the history

Directory Make & Remove

mkdir
subdir­ectorycreates new subdir­ectorymkdir subdir­/su­bsubdircreates subdir & subdir­/su­bsubdir
Hint: creates it, if they aren't existingrmdirremoves an empty dirrmdir /s directoryremoves directory with contentrmdir /s /q directoryremoves directory with content & skips y/n question

Directory copy

copy src dstcopy filescopy /Y src destcopy files overwrites with­out quesitonxcopy /s src destcopies dirs and subdirs except empty onesxcopy /YS src destas above with­out ask to overwritexcopy /YS src serv­er­sharecopy to network sharerobocopy /S src destcopies dirs and subdirs except empty onesrobocopy /YS src destas above without ask to overwrite

Parameters

%0Name of Script%1 ... %9Parameter 1 ... Parameter 9%*prints all parameters as a string(one line)
for %%x in (%*) do echo %%xaccess it through a for loop works with > 10 parameters

Pass Parameters to sub script

parame­ter­s_s­cri­pt.bat@echo off
call parame­ter­s_s­ubs­cri­pt.bat %*
EXIT /B %error­level%parame­ter­s_s­ubs­cri­pt.bat@ECHO off
echo subscript called with %*
EXIT /B 0EXIT /B specifies to exit the current batch scropt instead of cmd.exe. If executed from outside a batch script, it will quit cmd.exe

Arrays Way2

set array[0]=0
set array[1]=1
...set value to a specific array elementecho %array[0]%
echo %array[1]%access to array elementsmissing loop over elements: indexed

Functions: label and goto

echo 'Hi:'
goto :good:bad
echo 'I don't like scripting'
goto :eof:good
echo 'I like scripting'
goto :eof

Double­Cli­ckE­xec­ution

@ECHO off
setlocal
REM check for intera­ctive sesseion
SET intera­ctive=0
ECHO %CMDCM­DLINE% | FINDSTR /L %COMSPEC% >NUL 2>&1
IF %ERROR­LEVEL% EQ SET intera­ctive=1
ECHO do work
REM pause if intera­ctive (doubl­e-c­licked execution)
IF '­%in­era­cti­ve%­' '­0' PAUSE
EXIT /B 0FINDSTR /L is use search string literally

Navigation

realativeparent directorycd .., cd..subdir­ectorycd subdir­ectoyabsolutecd C:Windowscd Windowschange driveZ:

Wildcards

? (file?.txt)

Windows Bat File Cheat Sheet

one arbitary character* ( *.bat)arbitary characters (0,1 or more)

File Show

type fileshow file contentmoreshow file content page­wisesort fileshow file content sorted

Directory show Content

current folderdirabsolute pathdir C:Windowsdir Y:different drivedir /Bonly show file names and directory names

Batch Files User Input

@ echo off
set /P name='Input yor name: 'Syntax: set /P var=pr­ompt:echo Hi %name%variable call

Batch Files File Input

@echo off
echo Bill > file
echo Gate >> fileset /P fileco­ntent =< file
echo First Line: %filec­ontent%

Batch File Cheat Sheet Template

set /P var=< fileFOR /f %%f in (file) Do (
echo %%f
)REM print each line in file

Variables

setlocal
set MY_ENV=abc

Fun Batch File Codes

endlocalOnly active in the current batch file (local)set MY_ENV=abccreates or changes an enviro­nment variable that is active in the cmd. (global)setshows the active enviro­nment variablesecho %USERNAME%print variable outdefined MY_VARreturns
0 => Execution was successful
>0 => Execution failed

IF Control Structures

IF test (command) ELSE (command)Syntax

Control structures For

for {%%|%}­<Va­ria­ble> in (<S­et>) do <Co­mma­nd> [<C­omm­and­Lin­eOp­tio­ns>]cmd.exe use ->%batch script use ->­%%

Functions

call :print­_name Florianecho print_name exitst with %error­level%goto :eof:printname
echo Hit %1
exit /B 0 <- REM sets exit status of :print­_name

File Rename & Move

Cheatrename file1 file2renamef filte1 to file2move file1 dirmove file 1 to dir (path dir/file1)move file1 dir/file2moves and renames file1 to file2 (path: dir/file2) file2 is overwr­itten from file1move /Y file1 file2moves and overwrites file1 to file2 with­out asking

File Names

Case-I­nse­nsitiveMax. 260 characters incl. invisible termin­ating null characterspaces and character set 128 - 255 allowedNever <, >, :, ', /, , |, ?, *Hint: A-Z, a-z, 0-9, _, spaces, ( underscore as space )*.bat & *.cmddir /B --> only show file names and directory Names

Directory Rename & Move

rename dir1 dir2renames dir1 in dir2move dir1 dir2if dir2 exist: dir1 into dir2 (path: dir2/d­ir1), else rename dir1 to dir2move file1 dir/file2file 2 is deleted. file1 get the name of file2 ans is set at the position of file2 with asking (Yes/N­o/All)move /Y file1 file2file 2 is deleted. file1 get the name of file2 ans is set at the position of file2 with­out asking.

File Redirects

type file.txt | sortgive output of type to sortSheetsort < file.txtgive content ( stdin) of file.txtecho '­hi' > file.txtwrite '­hi' (stout) to file.txttype NUL > file.txtcreate empty filerm file 2> errors.txtredi­rects errors­(st­derr) ro errors.txtrm file 2> NULdiscard errorsrm file 2>&1redi­rect stderr to stdoutecho '­you­' >> file.txtappend '­you­' to file.txt

Comment

Batch File Cheat SheetREMPräfix after them the text

Calcul­ation

set /a i=0
echo i=%i%set /a i=1+1

Bat Cheat Sheet

Operatoren +, -, *, /set /a i+=1 Operatoren +, -, *, /

Arrays Way1

set arra­y=1 2 3 4
%array%(echo) all Array elementsfor %%a in (%array%) do (
echo%%a
)loop over elementsset array=­(and nothing else)unset vari­able or array

Control Struct­ures: Comparison Operators

OperatorInfoEqualEQUEqualNEQ!=Not equalLSS<LessLEQ<=Less than or equal toGTR>Greater thanGEQ>=Greater than or equalNOT!Not

Editors

NotepadNotepad++Visual­Stu­dioCode

Editors

NotepadNotepad++Visual­Stu­dioCodeAtom

Terminals

cmd.exeWindows TerminalConEmucmder

Batch Filex Exit / Return

Specify exit code:echo 'abc'
exit 0Query error levelecho %ERROR­LEVEL%

Windows Batch File Cheat Sheet

Exit/R­eturn codes0 => Execution was successful
>0 => Execution fiales with code X

For more information on a specific command, type HELP command-name

Batch File Cheat Sheet Example

CommandDescription
ASSOCDisplays or modifies file extension associations.
ATTRIBDisplays or changes file attributes.
BREAKSets or clears extended CTRL+C checking.
BCDEDITSets properties in boot database to control boot loading.
CACLSDisplays or modifies access control lists (ACLs) of files.
CALLCalls one batch program from another.
CDDisplays the name of or changes the current directory.
CHCPDisplays or sets the active code page number.
CHDIRDisplays the name of or changes the current directory.
CHKDSKChecks a disk and displays a status report.
CHKNTFSDisplays or modifies the checking of disk at boot time.
CLSClears the screen.
CMDStarts a new instance of the Windows command interpreter.
COLORSets the default console foreground and background colors.
COMPCompares the contents of two files or sets of files.
COMPACTDisplays or alters the compression of files on NTFS partitions.
CONVERTConverts FAT volumes to NTFS.
COPYCopies one or more files to another location.
DATEDisplays or sets the date.
DELDeletes one or more files.
DIRDisplays a list of files and subdirectories in a directory.
DISKCOMPCompares the contents of two floppy disks.
DISKCOPYCopies the contents of one floppy disk to another.
DISKPARTDisplays or configures Disk Partition properties.
DOSKEYEdits command lines, recalls Windows commands, and creates macros.
DRIVERQUERYDisplays current device driver status and properties.
ECHODisplays messages, or turns command echoing on or off.
ENDLOCALEnds localization of environment changes in a batch file.
ERASEDeletes one or more files.
EXITQuits the CMD.EXE program (command interpreter).
FCCompares two files or sets of files, and displays the differences between them.
FINDSearches for a text string in a file or files.
FINDSTRSearches for strings in files.
FORRuns a specified command for each file in a set of files.
FORMATFormats a disk for use with Windows.
FSUTILDisplays or configures the file system properties.
FTYPEDisplays or modifies file types used in file extension associations.
GOTODirects the Windows command interpreter to a labeled line in a batch program.
GPRESULTDisplays Group Policy information for machine or user.
GRAFTABLEnables Windows to display an extended character set in graphics mode.
HELPProvides Help information for Windows commands.
ICACLSDisplay, modify, backup, or restore ACLs for files and directories.
IFPerforms conditional processing in batch programs.
LABELCreates, changes, or deletes the volume label of a disk.
MDCreates a directory.
MKDIRCreates a directory.
MKLINKCreates Symbolic Links and Hard Links
MODEConfigures a system device.
MOREDisplays output one screen at a time.
MOVEMoves one or more files from one directory to another directory.
OPENFILESDisplays files opened by remote users for a file share.
PATHDisplays or sets a search path for executable files.
PAUSESuspends processing of a batch file and displays a message.
POPDRestores the previous value of the current directory saved by PUSHD.
PRINTPrints a text file.
PROMPTChanges the Windows command prompt.
PUSHDSaves the current directory then changes it.
RDRemoves a directory.
RECOVERRecovers readable information from a bad or defective disk.
REMRecords comments (remarks) in batch files or CONFIG.SYS.
RENRenames a file or files.
RENAMERenames a file or files.
REPLACEReplaces files.
RMDIRRemoves a directory.
ROBOCOPYAdvanced utility to copy files and directory trees
SETDisplays, sets, or removes Windows environment variables.
SETLOCALBegins localization of environment changes in a batch file.
SCDisplays or configures services (background processes).
SCHTASKSSchedules commands and programs to run on a computer.
SHIFTShifts the position of replaceable parameters in batch files.
SHUTDOWNAllows proper local or remote shutdown of machine.
SORTSorts input.
STARTStarts a separate window to run a specified program or command.
SUBSTAssociates a path with a drive letter.
SYSTEMINFODisplays machine specific properties and configuration.
TASKLISTDisplays all currently running tasks including services.
TASKKILLKill or stop a running process or application.
TIMEDisplays or sets the system time.
TITLESets the window title for a CMD.EXE session.
TREEGraphically displays the directory structure of a drive or path.
TYPEDisplays the contents of a text file.
VERDisplays the Windows version.
VERIFYTells Windows whether to verify that your files are written correctly to a disk.
VOLDisplays a disk volume label and serial number.
XCOPYCopies files and directory trees.
WMICDisplays WMI information inside interactive command shell.