Kristiaan Kristiaan - 1 year ago 118
Bash Question

Linux shell script - String trimming for dash

I am attempting to get the mac address from my Raspberry Pi take the last 6 characters of the mac to use as the hostname alongside a fixed string.

here is what I'v managed to get working from other sources so far, but I am now totally stuck trying to trim the string down.

#!/bin/sh -e

MAC="$( sed "s/^.*macaddr=\([0-9A-F:]*\) .*$/\1/;s/://g" /proc/cmdline )"


echo "$MAC1"

the shell being used by the Pi appears to be Dash, so the usual BASH commands that would have this done in no-time don't want to work or seem to generate errors when run within the script.

The full script that I am using in rc.local is below.

any advice on a way to-do this would be greatly received.

MAC="pi""$( sed "s/^.*macaddr=\([0-9A-F:]*\) .*$/\1/;s/://g" /proc/cmdline )"
echo "$MAC" > "/etc/hostname"
CURRENT_HOSTNAME=$(cat /proc/sys/kernel/hostname)
sed -i "s/*$CURRENT_HOSTNAME/\t$MAC/g" /etc/hosts
hostname $MAC

Answer Source

If you have the cut command on your Pi, you could do

MAC1=$( echo $MAC | cut -c 7-12 )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download