TransWikia.com

What is the meaning of tilde ~ in batch variables?

Super User Asked on November 4, 2021

I know from call /?, the ~ in variable (e.g. %~d1) is used to parse a part of file-path (driver here), but the tilde is used in another context here: https://www.tutorialspoint.com/batch_script/batch_script_string_length.htm:

@echo off
set str = Hello World
call :strLen str strlen
echo String is %strlen% characters long
exit /b

:strLen
setlocal enabledelayedexpansion

:strLen_Loop
   if not "!%1:~%len%!"=="" set /A len+=1 & goto :strLen_Loop
(endlocal & set %2=%len%)
goto :eof

Here, what is the meaning of this variable expansion: "!%1:~%len%!"? And how does it calculate the length of string via comparing it to empty string? What is the purpose of tilde here? Moreover, this example will get me into infinite loop where the output is if not "!str:~136!" == "" set /A len+=1 & goto :strLen_Loop (where the number !str:~n grows).

2 Answers

  • For "fix" this tutorial code and prevent your loop infinite, quoted in the commentary:

I see, but yet, in my machine I need to ^C to terminate it. Just look how big number I get - 136 - even though there is no length or word with 136 characters - @Herdsman

@echo off && setlocal enabledelayedexpansion

set "_str=Hello World" & call :strLen_Loop str

:strLen_Loop
if "%~1" == "" ( 
      endlocal & goto :EOF
    ) else if not "!_%~1:~%_len%!" == "" (
      set /A "_len+=1" & goto=:strLen_Loop
    ) else echoString is !_len! characters long & exit /b

Answered by Io-ol on November 4, 2021

The tilde (~) sign is used in different ways in batch files:

  • Argument quote removal. A tilde sign before an command-line argument (such as "%~1") indicates to remove the surrounding quotes from the parameter. Such if the value for %1 is "Hi" then %~1 will expand to only Hi.

  • Substring processing. There is a way to extract substring from a string variable in batch file. The syntax is: %variable:~num_chars_skip,num_chars_keep%. Num chars skip means the point where to start in the string, or to exclude how much characters preceding the string variable. And num chars to keep indicates the number of characters after the start point. Num chars to keep is optional, but first is mandatory. If num chars to keep is not specified, only that num chars to keep'th character will be parsed.

You should read these in command prompt for more help:

  • call /?
  • for /?
  • set /?

Hope that helps

Answered by programmer365 on November 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP