Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 377
  • Last Modified:

Help with batch functions and variables

My variables aren't behaving as expected. Can anybody tell me what I'm doing wrong and how to do it correctly?

The first snippet always fails regardless if the file exists or not.
The second snippet works as expected.

@echo off
if 1 == 1 (
type c:\21.bat >nul
call:errorcheck %errorlevel%
)
goto end

:errorcheck
set err=%~1
echo %err%
if "%err%" == "0" (
echo [ok]
) else (
echo [failed]
)
goto:eof

:end

Open in new window

@echo off
type c:\21.bat >nul
call:errorcheck %errorlevel%
goto end

:errorcheck
set err=%~1
echo %err%
if "%err%" == "0" (
echo [ok]
) else (
echo [failed]
)
goto:eof

:end

Open in new window

0
jasonzx
Asked:
jasonzx
  • 2
  • 2
1 Solution
 
oBdACommented:
That's "early" variable variable expansion.
The batch interpreter reads a statement in brackets as a single line and expands the variables in there when it reads this line.
In order to expand variables only when accessed, you need to enable delayed expansion and use ! to expand variables where necessary:
@echo off
setlocal enabledelayedexpansion
if 1 == 1 (
type c:\21.bat >nul
call:errorcheck !errorlevel!
)
goto end

Open in new window

0
 
jasonzxAuthor Commented:
Thanks oBdA, I'll try it at work on Monday(no Windows machines at home).
Do I have to replace  %err% with !err! inside of 'errorcheck' as well?
0
 
oBdACommented:
No, the normal expansion works just fine there.
The issue is described in the "set" help as well. Just enter "help set" in a command prompt.
0
 
QlemoC++ DeveloperCommented:
BTW, usually you should not use this way to test for existence of a file. Using "type" will still require the file to be read completely. It's better to use if exist:
@echo off
setlocal enabledelayedexpansion
if 1 == 1 (
  set err=0
  if not exist c:\21.bat set err=1
  call :errorcheck !err!
)
exit /b 0

Open in new window

I've also showed a way to end the batch file without using goto.
0
 
jasonzxAuthor Commented:
Thanks oBdA, that worked like a charm.

Qlemo:Thanks for the heads up, but that wasn't the real code I was having trouble with, just a stripped down and modified version to demonstrate the problem I was having.
0

Featured Post

Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now