Glam Prestige Journal

Bright entertainment trends with youth appeal.

After I run hostname I get the FQDN like so:

$ hostname
foo.mydomain.xyz

I'd like to only get the short name foo so I can store it as a variable in a script. I've tried some ways with awk by matching . (the dot) but haven't had much luck.

2 Answers

Using awk

$ echo foo.mydomain.xyz | awk -F. '{print $1}'
foo

awk takes its input by "records" (which defaults to lines) and each record is divided into "fields." By default, fields are separated by white space. Here, we change the default so that the field separator is a period. For this example, that means that the first field is foo, the second is mydomain, and the third is xyz. We tell awk to print only the first field, foo.

To capture the short name to a shell variable:

shortname=$(hostname | awk -F. '{print $1}')

Using sed

This problem can also be solved with sed:

$ echo foo.mydomain.xyz | sed 's/\..*//'
foo

Here, the substitution command, s/\..*//, simply looks for a period and removes the period and all that follows.

Using shell

$ name=foo.mydomain.xyz
$ name=${name%%.*}
$ echo $name
foo

It's not necessary to use sed, awk, grep. Just use the -s flag of hostname:

$ hostname -s
foo

From the man page:

 -s, --short Display the short host name. This is the host name cut at the first dot.
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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