0

I can't seem to assign an environment variable to another one inside a batch script.

For example, this will work:

set varA=C:\this\is\a\directory

and I can happily use

find /I "MyString" %varA%

without incident. However, if I try to assign it this way,

varA=%ENVVAR%\more\dirs

the batch just sticks in the CMD window until I stop it.

I'm still in the process of learning Windows' obnoxious unique scripting, so I can only speculate that it is throwing a fit over assigning a variable to another variable.

0

1 Answer 1

1

One thing you need to be careful of with setting variables in batch is not to use spaces unnecessarily. (I don't see this in your question, but wanted to call it out since I caught myself doing it while troubleshooting your issue.) For example:

set x=123

is not the same as

set x = 123

The former will set %x% to 123, while the latter will set %x % to 123. (Note the space after x in the variable name, and another one before 123 in the definition.)

Another thing to be aware of is you can't just say var=value. To set an environment variable, you must use the SET command.

So the proper syntax to set an environment variable that contains a path, and then one that expands upon that path, is as follows:

set x=C:\This\is\a\directory
set y=%x%\more\dirs

You can then use the SET command to verify the contents of these variables.

enter image description here

If you're just learning scripting languages in Windows though, it would probably be more useful for you to skip batch and jump straight into PowerShell. PowerShell comes standard with Windows Vista and above, and is also available for XP. Here's how the same job would be done in PowerShell.

$x='C:\This\is\a\directory'
$y="$x\more dirs"

(Note: There's a reason double-quotes were used when setting $y, while single-quotes were used for $x. In this case, we could have used either for setting $x but double-quotes were mandatory for setting $y since we needed to expand a variable. You'll learn more about that as you pick up the language.)

Then, to verify the variables, you can just call them directly.

enter image description here

PowerShell is also a lot less sensitive to spacing in most cases.

$x=123

is the same as

$x = 123
2
  • This doesn't quite answer it, but it turns out I was specifying a wrong (non-existent) directory entirely. I use %APPDATA% so frequently that I forgot it points to Roaming rather than the actual folder.
    – fishscarab
    Aug 20, 2014 at 20:07
  • @SacredCrumb Ah, then this becomes something of an XY Problem. Next time, instead of giving a general case for what you think is broken, provide the real details of what you're actually trying to do.
    – Iszi
    Aug 20, 2014 at 21:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .