xinta
xinta

Reputation: 9

How I can write the name of a file from a variable in Batch

I need to create a new file with the extension .bat using the value of a variable.

For example, I type "apple" and then the script should create a file called apple.bat. I believe the script should be

set /p nume=Type the name | fsutil file createnew %nume%.bat 100

but the result is "%nume%.bat" and not "apple.bat"

Upvotes: 1

Views: 3255

Answers (1)

mklement0
mklement0

Reputation: 437833

@SomethingDark's comment contains the crucial pointer: the fsutil command must be on a separate line in order to access the newly assigned %nume% variable.

Apart from that, you should use & (unconditional) or && (only if the command on the left succeeded) to chain commands; | (a pipe) only makes sense if you want output from the command on the left to serve as input to the command on the right. This does not apply here, as the set command doesn't produce output.

Therefore, use the following:

set /p name="Type a name: "
fsutil file createnew "%name%.bat" 100

Note how I've double-quoted the whole filename expression to ensure that it works correctly with names with embedded spaces.

The reason that these two commands must be on separate lines is that cmd.exe, the Windows command processor, expands all %<name>% variable references before a command is executed.
That is, %name% expands to whatever value variable name had before the value was prompted for with set; if that variable hasn't been set yet, literal %name% will print at the command prompt; by contrast, in a batch file the variable reference will expand to the empty string.

There is, however, a way to change this behavior: if you turn on delayed expansion, you can use
!<name>! variable references to have their values expanded delayed, i.e., to have their expansion happen at the time of access.

  • Interactively, you can turn this feature on by starting a new cmd.exe instance with option /V:ON.
cmd.exe /V:ON  # start a new cmd.exe instance with delayed expansion enabled
set /p name="Type a name: " && fsutil file createnew "!name!.bat" 100
  • In a batch file, use setlocal enabledelayedexpansion; note that setlocal creates a script-local scope for your variables, which, however, is generally desirable.

Upvotes: 2

Related Questions