Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
bash# hostname

I only want host1. So:


Can I turn this into a one liner? - or - what is the best way to make $SHORT_HOST readonly, but still get the short hostname?

share|improve this question

If you're not limited to just bash's tools, maybe try

SHORT_HOST=$(hostname | sed -e 's/\..*//')


SHORT_HOST=$(hostname | cut -d. -f1)
share|improve this answer

If your environment supports this, you could simply:

typeset -r SHORT_HOST="$(/bin/hostname -s)"
share|improve this answer

This is just another way using awk command:

/bin/hostname | awk -F'.' '{print $1}'

and if you need to store it in a SHORT_HOST variable use the following:

SHORT_HOST=$(/bin/hostname | awk -F'.' '{print $1}')
share|improve this answer

In shells other than zsh, you need to perform an intermediate assignment whenever you want to perform multiple transformations on a value.

Of course, there are sometimes workarounds, such as running a command that produces the desired result with no postprocessing or doing the postprocessing via a pipe through an external tool (the pipe solution will be slower and runs into more risk of mangling newlines).

If you want to make the variable read-only, you might find it cleaner to assign to a temporary variable.

typeset -r SHORT_HOST="${tmp%%.*}"

Zsh (but not ksh or bash) supports nested parameter substitutions. There, you can write

typeset -r SHORT_HOST=${$(/bin/hostname)%%.*}
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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