M HYPE SPLASH
// news

How do I assign the Output of a command as a Value of a variable?

By Andrew Adams

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

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

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

hname=$(hostname)

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy