如何在endlocal命令之后保留变量

时间:2013-04-06 08:25:35

标签: batch-file environment-variables

谢谢Nate。它有效。
但是现在我需要输出变量供这个脚本稍后使用 我需要2个输出。第一个是计数变量作为整数输出,第二个是字符串变量,它等于“word”中的最后一个字符串字符 所以,我需要这个2变量,就像你在“按任意键继续...”之前在最后一行完成的脚本中看到的那样 最后一个整数变量和最后一个字符串变量。

我需要这两个变量才能在此脚本中进行后续脚本编写 我怎么能拥有它? 这是一个从昨天起作用的脚本。

@ECHO OFF
:input
set /p word=input your word:
if not defined word goto input
(ECHO %word%)> tempfile.txt
FOR %%x IN (tempfile.txt) DO ( SET /A lenght=%%~zx - 2 )

del tempfile.txt
echo %word% got %lenght% characters
setlocal enabledelayedexpansion

for /l %%m in (1,1,!lenght!) do (
  set /a count=%%m
  set /a index=%%m-1
  call echo !count! %%word:~!index!,1%%
) 

(call echo %%word:~!index!,1%%)>tf.txt


for /f "tokens=*" %%a in (tf.txt) do (
set line=%%a
set char=!line:~0,1!

)

pause

echo %count% %char%

endlocal

pause

2 个答案:

答案 0 :(得分:2)

记录here的方法有很多,说明如何执行此操作,但endlocal & set global=local是我的最爱。

根据我的想法判断...

setlocal enabledelayedexpansion
for /l %%m in (1,1,!lenght!) do (
    set /a count=%%m
    set /a index=%%m-1
    call echo !count! %%word:~!index!,1%%
    set laststring=%word:~!index!,1%
) 
(
    endlocal
    set count=%count%
    set laststring=%laststring%
)

答案 1 :(得分:1)

尝试使用此技术拆除setlocal enabledelayedexpansion / endlocal

的墙
@echo off&setlocal
set "word=abcdefghij"
set /a lenght=10

for /l %%m in (1,1,%lenght%) do (
    set /a $count=%%m
    set /a index=%%m-1
    setlocal enabledelayedexpansion
    call echo !$count! %%word:~!index!,1%%
    call set "$laststring=%%word:~!index!,1%%"
    for /f %%i in ('set $') do (if "!"=="" endlocal)& set "%%i"
)
echo( 
echo !$count! !$laststring!
echo %$count% %$laststring%

source