Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Im not sure why running this command from the prompt does not work, can setlocal only be called from a batch file?

setlocal EnableDelayedExpansion & for /l %i in (1,1,3) do (set text=%i & echo Hello !text!)

The expected result is:

Hello 1
Hello 2
Hello 3

UPDATE: I am using Windows 8.1

share|improve this question

2 Answers 2

The question is the answer. You're clearly using Microsoft's cmd command interpreter in Windows NT; and in that command interpreter setlocal indeed has no effect when invoked outwith a command script.

Other command interpreters differ, in what setlocal does, in whether it can be invoked outwith a command script, in whether it nests, and in whether it controls the things that you are trying to control.

The original setlocal, in Microsoft's cmd in OS/2 version 1, just saved the current drive, directory, and environment; had no effect outwith command scripts; and didn't nest. As you can see, over the last quarter century the command has been extended in different directions.

One reason for a difference here is that JP Software's TCC performs variable expansion progressively in compound commands, and doesn't need the delayed variable expansion trick in order to do what you are trying to do. This:

for /l %i in (1,1,3) do (set text=%i & echo Hello %text%)
… prints what you want to print.

Further reading

  • SETLOCAL. Windows XP Command-line reference A–Z. TechNet. Microsoft corporation.
  • SETLOCAL. Take Command / TCC Help. JP Software.
  • Jonathan de Boyne Pollard. SETLOCAL. 32-Bit Command Interpreter command reference.
  • SETLOCAL. OS/2 Warp Command reference. IBM Corporation.
  • J. Emmett Beam (1988). Illustrated OS/2. Wordware Publishing. ISBN 9781556220531. p. 40
share|improve this answer
    
Thanks for the well informed answer, but unfortunately this is using the command interpreter from Windows 8.1. When running your command I get the output: Hello 3 Hello 3 Hello 3 –  Sparks Mar 6 at 5:05
up vote 0 down vote accepted

The answer turned out to be fairly simple!

for /l %i in (1,1,3) do (call set text=%i & echo Hello %text%)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.