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?

3
  • It is because the backticks are not around the whole command. Also prefer $() over backticks. see @clk 's answer for details on how. Jul 18, 2016 at 17:35
  • Does "${HOSTNAME%%.*}" work for you? HOSTNAME is not in POSIX though
    – iruvar
    Jul 18, 2016 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, 2016 at 11:57

1 Answer 1

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.

2

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.