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

Edward Q. Bridges picture Edward Q. Bridges · Jun 15, 2009 · Viewed 209.5k times · Source

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.

Answer

sean e picture sean e · Jun 15, 2009

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.