Help improve my scripting skills
August 29, 2007 6:55 AM
Subscribe
I wrote a shell script for an acquaintance that renames Macs (OS 10.4) based on their existing names. It works well, but I'm convinced my code could be more efficient. Where can I make improvements?
First, some background. The old naming scheme was [Building]_[CPU speed]_[Model]_[number]. The length of the names was cumbersome, so they decided to shorten them to [abbreviated building name]-[model]-[A/B][number], where A=1.42GHz and B=1.25GHz. For example, if the old names are
Berkeley_1.25Ghz_eMac_01
Washington_700MHz_iMac_01
the new names should be
berk-emac-B01
wash-imac-01 (they only have 700Mhz iMacs)
This is the bash script I came up with (with comments), that gets run as root on each computer:
# get the current computer name
NAME=`scutil --get ComputerName`
# split the name into its component parts
BLDG=`echo $NAME | awk -F_ '{print $1}'`
CPU=`echo $NAME | awk -F_ '{print $2}'`
MOD=`echo $NAME | awk -F_ '{print $3}'`
NUM=`echo $NAME | awk -F_ '{print $4}'`
# replace full building name with abbreviation
newBLDG=`echo $BLDG | sed \
-e 's/Berkeley/berk/' \
-e 's/Washington/wash/'`
# make model lowercase
newMOD=`echo $MOD | tr [:upper:] [:lower:]`
# replace cpu speed with letter (or no letter for 700MHz)
newCPU=`echo $CPU | sed \
-e 's/1.42GHz/A/' \
-e 's/1.25GHz/B/' \
-e 's/700MHz//'`
# reassemble name from new parts
newNAME=$newBLDG-$newMOD-$newCPU$NUM
# assign the new name to the computer
scutil --set ComputerName $newNAME
scutil --set LocalHostName $newNAME
posted by pmbuko to computers & internet (11 comments total)
posted by andrew cooke at 7:10 AM on August 29, 2007