7
bash# hostname
host1.example.com

I only want host1. So:

SHORT_HOST=$(/bin/hostname)
SHORT_HOST=${SHORT_HOST%%.*}

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?

4 Answers 4

5

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

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

or

SHORT_HOST=$(hostname | cut -d. -f1)
4

If your environment supports this, you could simply:

typeset -r SHORT_HOST="$(/bin/hostname -s)"
3

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}')
2

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.

tmp=$(/bin/hostname)
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)%%.*}

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.