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 $hnameBut 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?
1Hello, my server name is User
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.