3

I have a simple bash script like below :

#!/bin/bash

hname='hostname'
echo Hello, my server name is $hname

But the output is not as I expected. It is as below :

Hello, my server name is hostname

But my hostname is not 'hostname', it is actually 'User'. How should I make it seen as that?

Hello, my server name is User

1

3 Answers 3

4

If you want to get the output of a certain command as a string that should be assigned as value of a variable you need to use the command substitution builtin functionality:

#!/bin/bash
hname="$(hostname)"
echo "Hello, my server name is $hname"

Also you can use the old style of command substitution that is supported by bash (and dash/sh) and is the only one within some other shells:

#!/bin/bash
hname=`hostname`
echo "Hello, my server name is $hname"
0
1

If you want the variable hname to contain your hostname, use this syntax:

hname=$(hostname)

0

You want to use $HOSTNAME to get the variable. "hostname" will be treated as a constant.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .