views:

4506

answers:

5

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 Vista, WinXP, Win2k 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.

+3  A: 

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.

sean e
that works -- thanks
eqbridges
A: 

just create a bat file with the line

hostname

in it. That's it. Windows also supports the hostname command

jitter
sorry, i should have been more clear. wanted to use the value as stored in the variable, not simply echo it.
eqbridges
+6  A: 

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.

Dave Webb
very nice, though that for loop construct is heavily overloaded IMO. Will switch to use this. Thanks!
eqbridges
You're right - FOR is basically the swiss-army knife of batch scripts in that you end up using it to solve most problems.
Dave Webb
If you want to repeat the assignment (For this example it does not make sense, as you would only query the host name once in a run) then don't forget to use `SETLOCAL ENABLEDELAYEDEXPANSION` (see `HELP SETLOCAL`) and use `!MYVAR!` instead of `%MYVAR%`
PA
A: 

Why not so?:

set host=%COMPUTERNAME%
echo %host%
maniattico
A: 

exactly, here's how i'm using it:

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