Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Batch: What does the "~" do? [duplicate]

Tags:

batch-file

cmd

I was just wondering what the "~" symbol does in a batch file, I know that it's associated with variables.

Can I have some examples of what it does?

Thanks.

like image 761
Strictly No Lollygagging Avatar asked Apr 13 '26 21:04

Strictly No Lollygagging


1 Answers

It depends on the command on which ~ is used as dbenham and Magoo already wrote. In general it means: Get the value of a variable (loop or environment variable) or an argument string passed to the batch file with a modification.

A very simple example:

There is a batch file test.bat with content:

@echo Parameter 1 as specified: %1
@echo Parameter 1 (no quotes):  %~1

which is started with

test.bat "C:\Program Files\Internet Explorer\iexplore.exe"

The double quotes are necessary because of the spaces in path.

The batch file outputs:

Parameter 1 as specified: "C:\Program Files\Internet Explorer\iexplore.exe"
Parameter 1 (no quotes):  C:\Program Files\Internet Explorer\iexplore.exe

So in this example ~ results in getting value of first parameter without double quotes.

As dbenham already wrote, enter in a command prompt window following commands and read the help output in the window.

  1. help call or call /?
  2. help for or for /?
  3. help set or set /?

On many commands strings with spaces or other special characters – see last help page output after entering cmd /? – must be enclosed in double quotes. But others require that the double quotes are removed like on a comparison of two double quoted strings with command if or the double quotes are not wanted like on using echo.

One more example:

@echo off
if /I "%~n1" == "iexplore" echo Browser is Internet Explorer.
if /I "%~n1" == "opera" echo Browser is Opera.
if /I "%~n1" == "firefox" echo Browser is Firefox.

On this example ~n results in just getting the file name without double quotes, path and file extension from string passed as first parameter to the batch file.

Argument 0 is the currently executed batch file as it can be demonstrated with:

@echo off
echo Batch file was called with: %0
echo Batch file is stored on drive:  %~d0
echo Batch file is stored in folder: %~dp0
echo Batch file name with extension: %~nx0
like image 187
Mofi Avatar answered Apr 16 '26 00:04

Mofi