Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store a NULL ASCII character (nul) in a variable with a Windows batch script?

Following the post How can I write a null ASCII character (nul) to a file with a Windows batch script? there are indeed methods to write an ASCII NULL character (nul) to a file with a batch script.

However, I cannot find a way to store a NULL character to a variable.

Supposing the file null.nil contains a single NULL character, redirecting it into set /P does not seem work, the variable appears empty:

< "null.nil" set /P NULL=
set NULL

for /F does not appear to work either as it seems to dismiss every NULL character it encounters. Relying on the same file null.nil, the following results in an empty variable:

for /F %%S in ('type "null.nil"') do set NULL=%%S
set NULL

Changing the set syntax to set "NULL=%%S" or to set NULL=^%%S does not change anything, although the command line type "null.nil" does echo the NULL character (on my Windows 10 x64 machine; redirect type output to a file and view it with a hex. editor).

So how can I set a variable to a single NULL character? The NULL character can either be taken from a file (like null.nil) or generated by some smart hack, but I do not want it to be embedded in the batch file directly.

like image 896
aschipfl Avatar asked Aug 04 '16 21:08

aschipfl


1 Answers

According to the page Environment Variables of Microsoft's MSDN Library and also to the post Setting environment variables for a specific run of a specific process, the environment block is stored in a NULL-terminated block of NULL-terminated strings -- here quickly illustrated in EBNF notation:

environment-block = { variable-definition } , null-char ;
variable-definition = variable-name , '=' , variable-value , null-char ;

Due to this storage format it is not possible to store a NULL character into an environment variable. Even if one managed to get a NULL written to the environment block it could not ever be read again.

like image 129
aschipfl Avatar answered Sep 18 '22 13:09

aschipfl