I’m writing a bash script for a computer lab. Usually when we update the computers we use a single image that we clone for all the computers. The problem is that all the computers get the same hostname.
So I decided to write a bash script that reads the mac address of the PC and then changes the hostname according to a table.
I’m using a case statement, but I want to use a separate config file. How can I do that?
This is the script (see the uncomfortable case):
#!/bin/bash
if [[ $(/usr/bin/id -u) -ne 0 ]]; then
echo 'Errore, non sei root!'
exit 1
else
mac=$(cat /sys/class/net/eth0/address)
basename='Lab121Pc'
case $mac in
'c8:9c:dc:d2:82:2c') id='01';;
'c8:9c:dc:d2:81:f4') id='02';;
'c8:9c:dc:d2:46:3e') id='03';;
'c8:9c:dc:d2:82:33') id='05';;
'c8:9c:dc:d2:81:96') id='06';;
'c8:9c:dc:d2:83:55') id='07';;
'c8:9c:dc:d2:2f:14') id='09';;
'c8:9c:dc:d2:82:45') id='10';;
'c8:9c:dc:d2:82:2f') id='11';;
'c8:9c:dc:d2:51:2e') id='12Hp';;
'c8:9c:dc:d2:7e:43') id='13';;
'c8:9c:dc:d2:49:ba') id='14';;
'c8:9c:dc:d2:81:f3') id='15';;
'c8:9c:dc:d2:7e:3c') id='17';;
'c8:9c:dc:d2:7e:33') id='18';;
'c8:9c:dc:d2:83:62') id='19';;
'c8:9c:dc:d2:4a:db') id='21';;
'c8:9c:dc:d2:e3:d4') id='22Hp';;
'c8:9c:dc:d2:7e:e7') id='23';;
'c8:9c:dc:d2:b0:f4') id='24Hp';;
'c8:9c:dc:d2:49:e8') id='25';;
'c8:9c:dc:d2:82:31') id='26';;
'c8:9c:dc:d2:81:2f') id='27';;
'c8:9c:dc:d2:48:5c') id='28';;
'c8:9c:dc:d2:81:e6') id='29';;
'c8:9c:dc:d2:81:36') id='30';;
esac
hostname=$basename$id
if [ $(cat /etc/hostname) == $hostname ]; then
echo 'Hostname e'' gia'' corretto'
exit 0
else
echo 'Hostname errato, correzzione in corso...'
echo $hostname > /etc/hostname
echo 'Aggiornamento riuscito'
exit 0
fi
fi
Thank to all.
I’m using Linux and I can’t use DHCP, but anyway thank you, it probabily will ber useful in other moments.
However, I fount the cut command, so i’v created i file containing the mac addresses:
xx:xx:xx:xx:xx:xx 01
xx:xx:xx:xx:xx:xx 02
xx:xx:xx:xx:xx:xx 03
xx:xx:xx:xx:xx:xx 04
xx:xx:xx:xx:xx:xx 05
So, I can scroll the lines of the file and then uses cut
cut -d ' ' -f 1 macs
The delimeter is the space, so if I want the mac address I put the -f value to 1 or if I want the id to 2.
If you format your file like:
Then you can do something like:
(But I agree with the comment on your question: the best way of doing that would be through DHCP.)