0

is there some redirect from a string to a variable in batch?

main.cmd

@setlocal enableextensions Enabledelayedexpansion 
@echo off
set log=C:\log\test.log
set my_var=foo
set vars_to_check=my_var
call check_empty.cmd "%vars_to_check%"  || goto :error_handler

check_empty.cmd

if "%1" == "" (
    echo no param. >> !log!
    exit /b 2
    )
if not defined %1 ( 
    echo the variable %1 is empty.  >> !log!
    exit /b 1 
    )
echo %1 has value %%1%%.   >> !log!
exit /b 0

Now I did run main.cmd: I did expect the echo 'my_var has value foo.'. However, I just get 'the variable "%1" is empty.' Please note the quotes around %1. Therefore, I removed the quotes from the call in main.cmd and it almost worked, as I got the message: 'my_var has value %my_var%.'. At least I am arriving at the point where the variable is realized to be defined.

The problem with avoiding the quotes is that the next step would have been: pass multiple vars and loop the check...

set vars_to_check=my_var some_other_var something_else

and now I need the quotes so I can pass the variable...

1
  • Perhaps you should publish what your expectations of the check batch would be. Do you want a return errorlevel, test written to the console or file reporting the status of each variable in the list, or perhaps a variable reporting which variables were/were not defined? Commented Dec 31, 2020 at 10:51

1 Answer 1

3

check_emtpy.cmd:

@echo off
if "%~1" == "" echo no param. & exit /b 2
if not defined %~1 echo the variable %1 is empty.& exit /b 1
call echo %1 has value %%%~1%% & exit /b 0
  • if the parameter (variable name) is empty, return (errorlevel 2)
  • if the variable isn't defined, return (errorlevel 1)
  • return (errorlevel 0)

If you don't need the message, the last line is optional. If you can guarantee that there is always a parameter (but who could guarantee that...), the first if is optional too.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.