StackOverflow have another interesting topic about: Underused features of Windows batch files.
Of course there are many things I didn’t know about. Some highlights:
PUSHD path
Takes you to the directory specified by path.
POPD
Takes you back to the directory you “pushed” from.
By using CALL, EXIT /B, SETLOCAL & ENDLOCAL you can implement subroutines with local variables.
example:
@echo off
set x=xxxxx
call :sub 10
echo %x%
exit /b:sub
setlocal
set /a x=%1 + 1
echo %x%
endlocal
exit /bThis will print
11
xxxxxeven though :sub modifies x.
Creating an empty file:
> copy nul filename.ext
The equivalent of the bash (and other shells)
echo -n Hello # or
echo Hello\\cwhich outputs “Hello” without a trailing newline. A cmd hack to do this:
<nul set /p any-variable-name=Hello
set /p is a way to prompt the user for input. It emits the given string and then waits, (on the same line, i.e., no CRLF), for the user to type a response.
<nul simply pipes an empty response to the set /p command, so the net result is the emitted prompt string. (The variable used remains unchanged due to the empty reponse.)
Problems are: It’s not possible to output a leading equal sign, and on Vista leading whitespace characters are removed, but not on XP.
Command separators:
cls & dir
copy a b && echo Success
copy a b || echo FailureAt the 2nd line, the command after && only runs if the first command is successful.
At the 3rd line, the command after || only runs if the first command failed.
Doesn’t provide much functionality, but you can use the title command for a couple of uses, like providing status on a long script in the task bar, or just to enhance user feedback.
@title Searching for …
:: processing search
@title preparing search results
:: data processing
And there are many more. If you want to learn something new, this topic is must have reading!
Thanks for some interesting tips on the command prompt. Another way to create a empty file could be with the fsutil command:
fsutil file createnew file.txt 0 (replace the zero with any other size to create large files)
Another old copy command is the small “editor” with:
copy con file1.txt
write some text
CTRL+Z to save
Rickard Nobel,
Thanks for the info. The downside of fsutil is that it requires Admin privileges.