0

When I enter "hostname" into the Windows Command Prompt, I get the expected hostname of the system, but I can't seem to include it in any string output, either assigned to another variable, or just as itself.

The below script outputs "Ready to copy to Server of Is this the correct location?" and all variations of using hostname seem to result in the same.

@echo off 
set hostnamevar=%hostname%
set "greeting1=Ready to copy to Server of "
set "greeting2=Is this the correct location?"
set "greeting=%greeting1%%hostnamevar%%greeting2%"
echo %greeting%
pause 
aschipfl
  • 33,626
  • 12
  • 54
  • 99
David Metcalfe
  • 2,237
  • 1
  • 31
  • 44
  • 2
    Try `for /f %%A in ('hostname') do set hostname=%%A`. The `hostname` program is not an environment variable. This is one way to run the program and set the output as a variable. Every time I see code like this I'm reminded why I use Bash, even in Windows. – paddy Sep 15 '15 at 03:41
  • to understand, what is hostname here? a command? a variable? hostname /? give command unknown even with echo %hostname% but if I type hostname on console, it show a weird output. `Server : UnKnown Address: 2001:4860:4860::8888` – Paul Sep 15 '15 at 03:47
  • Actually this post is _very_ similar to [this one](http://stackoverflow.com/a/23029303/5047996) (the second code snippet)... – aschipfl Sep 15 '15 at 12:41
  • 1
    Oh wait, my cmd was stuck in nslookup command, this is why the hostname command was not recognized, sorry. (I will remove all my comments in a short time) – Paul Sep 15 '15 at 18:18

1 Answers1

2

Here, hostname is set as an environment variable now.

@ECHO OFF
FOR /F %%H IN ('hostname') DO SET hostnamevar=%%H
SET Greeting=Ready to copy to Server of "%hostnamevar%" Is this the correct location?
ECHO %Greeting%
PAUSE

A little note, on this section, SET Greeting=Ready to copy to Server of "%hostnamevar%" Is this the correct location? you don't need the encapsulating "" around %hostnamevar%

Potato Head
  • 143
  • 1
  • 8
  • Not sure I follow on your comment. If the encapsulating quotations around %hostnamevar% aren't necessary, then why have them? – David Metcalfe Sep 15 '15 at 23:41
  • 1
    Just me being me in all honesty, if that were my code, I like my eye to be drawn to the variable just for verification that the variable is in fact changing. but the code will execute proper with simply inserting %hostnamevar% where ever you want, if you wanted to you could set the title of the batch window to the hostname. TITLE %hostnamevar% – Potato Head Sep 16 '15 at 04:37