How to store the hostname in a variable in a .bat file?

I would like to convert this /bin/sh syntax into a widely compatible Windows batch script:

host=`hostname`
echo ${host}

How to do this so that it'll work on any Windows Vista, Windows XP, and Windows 2000 machine?

To clarify: I would then like to go on in the program and use the hostname as stored in the variable host. In other words, the larger goal of the program is not to simply echo the hostname.


hmm - something like this?

set host=%COMPUTERNAME%
echo %host%

EDIT: expanding on jitter's answer and using a technique in an answer to this question to set an environment variable with the result of running a command line app:

@echo off
hostname.exe > __t.tmp
set /p host=<__t.tmp
del __t.tmp
echo %host%

In either case, 'host' is created as an environment variable.


I usually read command output in to variables using the FOR command as it saves having to create temporary files. For example:

FOR /F "usebackq" %i IN (`hostname`) DO SET MYVAR=%i

Note, the above statement will work on the command line but not in a batch file. To use it in batch file escape the % in the FOR statement by putting them twice:

FOR /F "usebackq" %%i IN (`hostname`) DO SET MYVAR=%%i
ECHO %MYVAR%

There's a lot more you can do with FOR. For more details just type HELP FOR at command prompt.


I'm using the environment variable COMPUTERNAME:

copy "C:\Program Files\Windows Resource Kits\Tools\" %SYSTEMROOT%\system32
srvcheck \\%COMPUTERNAME% > c:\shares.txt
echo %COMPUTERNAME%

Why not so?:

set host=%COMPUTERNAME%
echo %host%