1

I want to extract the host name of a machine and omit whatever exists after .. For example, the command hostname says compute-0-0.local. So, I used `cut command like this

# hostname | cut -f 1 -d "."
compute-0-0

Now, I want to put that output in a variable. The following command doesn't work.

# HT=`hostname` | cut -f 1 -d "."
# echo $HT
compute-0-0.local

Any way to fix that?

mahmood
  • 1,211
  • It is because the backticks are not around the whole command. Also prefer $() over backticks. see @clk 's answer for details on how. – ctrl-alt-delor Jul 18 '16 at 17:35
  • Does "${HOSTNAME%%.*}" work for you? HOSTNAME is not in POSIX though – iruvar Jul 18 '16 at 18:00
  • 1
    assuming Linux (or other OS with a reasonably modern and useful hostname command), you could just use hostname -s aka hostname --short. – cas Jul 19 '16 at 11:57

1 Answers1

4

Use this instead, noting that your entire command must be enclosed within the backticks:

HT=`hostname | cut -f 1 -d "."`

You could potentially use $() as well:

HT=$(hostname | cut -f 1 -d ".")

This syntax for command substitution is not supported in certain shells, though, including the original Bourne shell, csh and tcsh. For those shells you will need to use backticks.

clk
  • 2,146
  • 1
    Note that backticks aren't always a matter of preference: http://unix.stackexchange.com/questions/218060/which-shells-dont-support-dollar-parenthesis-expansion-and-demand-backticks – Joshua Griffiths Jul 18 '16 at 18:58
  • @DWORDPTR Thanks for mentioning that. I've updated my answer to reflect that. – clk Jul 18 '16 at 19:16