Bash script to read a hostname and separate into variables

Hi All,

I'm trying to concoct a bash script to use with a Puppet Implementation that will accept a hostname and break it down into variables.

For example, my hostnames look like this --> machinename-group-building.example.com

I'm looking for a way in the script to read until the first hypen (run it like --> "/usr/bin/hostnamescript machinename-group.building.example.com"), and assign the "machinename" into a variable, read to the second hyphen and assign the "group" into a variable, and then read until the period and assign the "building" into the final variable - disregarding the rest.

What would be the easiest way to tackle this? Thanks!

off the top of my head, this should work:

machine=`echo $hostname | awk -F'-' '{print $1}'`
group=`echo $hostname | awk -F'-' '{print $2}'`
building=`echo $hostname | awk -F'-' '{print $3}' | sed 's/\..*//'`

I'm sure there is a better way. There is always 17+ ways to skin the cat.

That works! Thanks a million!

#!/bin/sh

hostname=$1

#first=`echo $1 | cut -d '-' -f1`
#two=`echo $1 | cut -d '-' -f2`
#three= `echo $1 | cut -d '-' -f3`

one=`echo $hostname | awk -F'-' '{print $1}'`
two=`echo $hostname | awk -F'-' '{print $2}'`
three=`echo $hostname | awk -F'-' '{print $3}' | sed 's/\..*//'`

echo "One: [$one]"
echo "Two: [$two]"
echo "Three: [$three]"

Here is another way using an array. I reassigned the values to meaningful variables, but that's optional.

#!/bin/bash

var=($( echo $1 | sed -e 's/^\([[:alnum:]]*\)-\([[:alnum:]]*\).\([[:alnum:]]*\)\.[.[:alnum:]]*$/\1 \2 \3 /g' ))

host=${var[0]}
group=${var[1]}
building=${var[2]}

printf "host=%s\ngroup=%s\nbuilding=%s\n" $host $group $building

exit 0

output:

./post302328860.sh machinename-group.building.domain.com
host=machinename
group=group
building=building

I know you asked for bash, but here is a simple perl script:

#!/usr/bin/perl -w
use warnings;
use strict;
m/^(\w+)-(\w+)\.(\w+)\.[\.\w]*$/;
my ($machine $group $building)=($1,$2,$3);
print "machine=$machine\ngroup=$group\nbuilding=$building\n";

-B

Shell parameter expansion. There's no need for an external command:

name=machinename-group-building.example.com
right=${name##*-*-}
hostnamescript "${name%"-$right"}.$right"