Echo length of a variable from the windows command line - windows

So I'm looking for a quick command to evaluate the length of environment variables on the windows command line.
Conceptually, something to the effect of:
echo %PATH%.length
Thanks!

#echo off
setlocal enabledelayedexpansion
call :COUNT "%path%"
echo Your variable is %length% characters long
pause >nul
:COUNT
set temp=%1
set length=0
:loop
if defined temp (
set temp=!temp:~1!
set /a length+=1
goto :loop
)
Usage: call :COUNT %yourvar% and the length will be stored in %length%.

Related

Windows Batch SET with Variable Substring Length?

Take this simple example:
#ECHO OFF
SET /P phrase="Enter Word : "
SET /a rnum=%random% %%10 +1
ECHO %phrase%
ECHO %rnum%
SET rchar=%phrase:~0,%rnum%%
ECHO %rchar%
Pause
I just want to be able to pass that rnum variable to pick that as the character chosen from the left of that user entered word to that random character.
I can't seem to figure out how to pass that as a variable.
I tried with enabledelayedexpansion with no luck:
#ECHO OFF
SET /P Phrase="Enter Word : "
SET /a rnum=%random% %%10 +1
ECHO %phrase%
ECHO %rnum%
setlocal enabledelayedexpansion
SET rchar=!phrase:~0,%rnum%!
endlocal
ECHO %rchar%
Pause
So how do I pass rnum as a variable in this instance? Thanks for any assistance.
Here's a simple modification of your example delayed expansion code, which shows one method of maintaining your variable value beyond endlocal:
#ECHO OFF
SET /P "phrase=Enter Word : "
SET /A rnum = %RANDOM% %% 10 + 1
ECHO %phrase%
ECHO %rnum%
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%G IN ("!phrase:~0,%rnum%!") DO ENDLOCAL & SET "rchar=%%~G"
ECHO rchar=%rchar%
PAUSE
The above example should be fine, as long as the end user does not begin to input strings with problematic characters. If you wanted to make it a little more robust for such scenarios then perhaps this will help:
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
:AskString
Rem Get interactive string input
Set "String="
Set /P String="Enter Word : "
If Not Defined String GoTo AskString
Set String
Rem Generate a random integer 1..10
Set /A "Integer = (%RANDOM% %% 10) + 1"
Set Integer
Rem Create a substring variable using %String% and %Integer%
Echo %%SubString%% = %%String:~0,%Integer%%%
SetLocal EnableDelayedExpansion
For /F Delims^=^ EOL^=^ UseBackQ %%G In ('"!String:~0,%Integer%!"') Do (
EndLocal
Set "SubString=%%~G"
)
Set SubString
Pause
Please note that the above code uses Set Variable to display the variable name along side its value. If your variable contains certain poison characters just using Echo %Variable% may not work, and you would probably be better off keeping delayed expansion enabled at that time.
As Compo already comments, the position of your endlocal is the problem.
You could just move the endlocal after the echo
#ECHO OFF
setlocal enabledelayedexpansion
SET /P Phrase="Enter Word : "
SET /a rnum=%random% %%10 +1
ECHO !phrase!
ECHO !rnum!
SET "rchar=!phrase:~0,%rnum%!"
ECHO !rchar!
endlocal

How to limit a batch variable's length

Is it any way to limit the length of a batch variable? I mean, if it is possible to program a variable that only admits between 0 and x characters? So, for an instance, if I entered 123456 and the max length was 4 it wouldn't proceed to continue. I hope you can understand my question.
Thanks in advance.
Demonstration batch code according to suggestions of aschipfl and rojo:
#echo off
setlocal EnableExtensions EnableDelayedExpansion
:UserPrompt
cls
set "UserInput="
set /P "UserInput=Enter string with a length between 1 and 4: "
if not defined UserInput goto UserPrompt
if not "!UserInput:~4!" == "" goto UserPrompt
echo/
echo String entered: !UserInput!
echo/
endlocal
pause
!UserInput:~4! is replaced by command processor on execution of the batch file by the string from user input starting with fifth character. First character of a string value has index value 0 which is reason for number 4 for fifth character. This string is empty if user entered a string not longer than 4 characters, otherwise this substring is not empty resulting in user must input again a string.
Delayed expansion is used to avoid an exit of batch processing caused by a syntax error if the user enters a string containing an odd number of double quotes.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
cls /?
echo /?
endlocal /?
if /?
pause /?
set /?
setlocal /?
If you mean "limit the length of a batch variable when it is read via SET /P command", then you may use the ReadLine subroutine described at this post, that emulates SET /P command using pure Batch file commands, and just insert the maximum length restriction.
#echo off
setlocal
call :ReadNChars string4="Enter 4 characters maximum: " 4
echo String read: "%string4%"
goto :EOF
:ReadNChars var="prompt" maxLen
rem Read a line emulating SET /P command
rem Antonio Perez Ayala
rem Initialize variables
setlocal EnableDelayedExpansion
echo > _
for /F %%a in ('copy /Z _ NUL') do set "CR=%%a"
for /F %%a in ('echo prompt $H ^| cmd') do set "BS=%%a"
rem Show the prompt and start reading
set /P "=%~2" < NUL
set "input="
set i=0
:nextKey
set "key="
for /F "delims=" %%a in ('xcopy /W _ _ 2^>NUL') do if not defined key set "key=%%a"
rem If key is CR: terminate input
if "!key:~-1!" equ "!CR!" goto endRead
rem If key is BS: delete last char, if any
set "key=!key:~-1!"
if "!key!" equ "!BS!" (
if %i% gtr 0 (
set /P "=!BS! !BS!" < NUL
set "input=%input:~0,-1%"
set /A i-=1
)
goto nextKey
)
rem Insert here any filter on the key
if %i% equ %3 goto nextKey
rem Else: show and accept the key
set /P "=.!BS!%key%" < NUL
set "input=%input%%key%"
set /A i+=1
goto nextKey
:endRead
echo/
del _
endlocal & set "%~1=%input%"
exit /B
However, if you want to limit the length of a Batch variable in other cases, like SET /A or plain SET commands, then there is no way to do that. Of course, you may execute such commands and then cut the variable value to the maximum length, but that process is an entirely different thing.

Print variable in batch file

I am trying to print a variable in parenthesised code which is assigned a value using other variable in batch file.
Here is my code
#echo off
SETLOCAL enableDelayedExpansion
CALL initialize
CALL fun
:fun (
#echo off
Setlocal EnableDelayedExpansion
Set "SOMEVAR=!OTHERVAR!"
ECHO ..%SOMEVAR%
EXIT /B 0
)
:initialize (
set SOMEVAR=somevalue
EXIT /B 0
)
The output is just
..
How do i fix it so that i can assign value to somevar?
Edit1: If i now try to print in following way it does its job
ECHO ..!SOMEVAR!
But my script uses lot of %SOMEVAR%. Does that mean i need to change them all?
Note: Othervar is initialzed in other function and it does show proper value if it is echoed.
Since the code portion containing echo %SOMEVAR% is in between parenthesis, the variable is expanded before being set (consult this post for a good explanation).
There are the following options to avoid that:
to expand it like !SOMEVAR! (delayed expansion), or
to avoid the parenthesis:
#echo off
SETLOCAL EnableDelayedExpansion
CALL initialize
CALL fun
exit /B
:fun
Setlocal EnableDelayedExpansion
Set "SOMEVAR=!OTHERVAR!"
ECHO ..%SOMEVAR%
EXIT /B 0
:initialize
set SOMEVAR=somevalue
EXIT /B 0
Note the additional exit /B in the above code snippet after the call statements, which prevents from falling into the code below unintentionally.
Does this work any closer to your expectations? Note that SOMEVAR will not be returned to your shell environment unless an ENDLOCAL block is used.
C:>set OTHERVAR=0123456789
C:>type g2.bat
#echo off
SETLOCAL enableDelayedExpansion
CALL:initialize
CALL:fun
EXIT /B 0
:fun (
rem #echo off
Setlocal EnableDelayedExpansion
Set "SOMEVAR=!OTHERVAR!"
ECHO ..%SOMEVAR%
GOTO :EOF
)
:initialize (
set SOMEVAR=somevalue
GOTO :EOF
)
C:>g2.bat
..0123456789

control both start and end of while loop using variable in windows bat script

I can do a while loop in DOS batch file like this:
#REM initialize test value to be "true"
#SET intCounter=1
:while
#REM test condition
#IF %intCounter% GTR 10 (GOTO wend)
#REM procedure where condition is "true"
#echo %intCounter%
#REM set new test value
#SET /a intCounter=intCounter+1
#REM loop
#GOTO while
:wend
#PAUSE
This will loop ten times.
My question are two folds.
How can I also control the end of the loop. I tried set end =1 and replace 10 with %end%, this does not work.
How to read input from keyboard and set them into iniCounter and end.
Thanks a lot.
I don't know what you did, but
#set end=5
:while
#IF %intCounter% GTR %end% (GOTO wend)
does work,or
#set /p end="Enter the end:"
if you want it to be entered by the user
And since your question is tagged 'windows', you might be better off with
set /p start="From:"
set /p end="To:"
for /l %%i in (%start%, 1, %end%) do (
echo %%i
)

Get last command line argument in windows batch file

I need to get last argument passed to windows batch script, how can I do that?
This will get the count of arguments:
set count=0
for %%a in (%*) do set /a count+=1
To get the actual last argument, you can do
for %%a in (%*) do set last=%%a
Note that this will fail if the command line has unbalanced quotes - the command line is re-parsed by for rather than directly using the parsing used for %1 etc.
The easiest and perhaps most reliable way would be to just use cmd's own parsing for arguments and shift then until no more are there.
Since this destroys the use of %1, etc. you can do it in a subroutine:
#echo off
call :lastarg %*
echo Last argument: %LAST_ARG%
goto :eof
:lastarg
set "LAST_ARG=%~1"
shift
if not "%~1"=="" goto lastarg
goto :eof
An enhanced version of joey's answer:
#ECHO OFF
SETLOCAL
:test
:: https://stackoverflow.com/a/5807218/7485823
CALL :lastarg xxx %*
ECHO Last argument: [%XXX%]
CALL :skiplastarg yyy %*
ECHO skip Last argument: [%yyy%]
GOTO :EOF
:: Return all but last arg in variable given in %1
:skiplastarg returnvar args ...
SETLOCAL
SET $return=%1
SET SKIP_LAST_ARG=
SHIFT
:skiplastarg_2
IF NOT "%~2"=="" SET "SKIP_LAST_ARG=%SKIP_LAST_ARG% %1"
SHIFT
IF NOT "%~1"=="" GOTO skiplastarg_2
ENDLOCAL&CALL SET "%$return%=%SKIP_LAST_ARG:~1%"
GOTO :EOF
:: Return last arg in variable given in %1
:lastarg returnvar args ...
SETLOCAL
SET $return=%1
SET LAST_ARG=
SHIFT
:LASTARG_2
SET "LAST_ARG=%1"
SHIFT
IF NOT "%~1"=="" GOTO lastarg_2
ENDLOCAL&call SET %$return%=%LAST_ARG%
GOTO :EOF
Run it with the arguments:
abe "ba na na" "cir cle"
and get:
Last argument: ["cir cle"]
skip Last argument: [abe "ba na na"]
set first=""
set last=""
for %%a in (%*) do (
SETLOCAL ENABLEDELAYEDEXPANSION
if !first!=="" (set first=!last!) else (set first=!first! !last!)
set last=%%a
)
ENDLOCAL & set "last=%last%" & set "first=%first%"
echo %last% "and" %first%

Resources