Getting IP and MAC Address from BASH/Shell Script

Ever wondered how to get your IP address and MAC address and then use it in a Linux shell script? Here’s how:


IP=$(ip addr show wlan0 | awk '/inet / {print $2}' | cut -d/ -f 1)
MAC=$(ip link show wlan0 | awk '/ether/ {print $2}')

echo "IP Address: $IP"
echo "MAC Address: $MAC"

# EndOfFile

You can change the wlan0 into whatever device you have, e.g. eth0.

Looping Through Files with Spaces and Special Characters in BASH

This is useful for batch processing of files with special characters such as space, ampersand (&), underscore, etc. The example below is to do mass conversion of mp4 files I downloaded from youtube into mp3 files.

Instead of giving the command directly, I prefer always to “echo” the command so I can see whether it’s giving the desired batch command or not. If all okay, then remove the echo.

$ find ./ -type f | sed 's/.mp4//' | sed 's/\.\///' | while read FILE;
echo ffmpeg -i \"$FILE.mp4\" -ab 192k \"$FILE.mp3\";

But the with the above script, somehow ffmpeg won’t accept the filenames – although I already put quote in both end. Strange enough, if I give the command directly for example:
$ ffmpeg -i "Some file (3_11)_.mp4"
It works.

Let’s just focus on getting the job done shall we? The easiest workaround is by redirecting the output of the script above into a file by putting
in the end of the script (right after “done”). So the batch file will look like this:

ffmpeg -i "Chaka Khan _ I'm Every Woman _(360p_H.264-AAC).mp4" -ab 192k "Chaka Khan _ I'm Every Woman _(360p_H.264-AAC).mp3"
ffmpeg -i "David Foster _ Winter Games _(360p_H.264-AAC).mp4" -ab 192k "David Foster _ Winter Games _(360p_H.264-AAC).mp3"
ffmpeg -i "Earth, Wind & Fire (3_11) - Fantasy(360p_H.264-AAC).mp4" -ab 192k "Earth, Wind & Fire (3_11) - Fantasy(360p_H.264-AAC).mp3"
ffmpeg -i "Earth, Wind & Fire (4_11) - Sing a song(360p_H.264-AAC).mp4" -ab 192k "Earth, Wind & Fire (4_11) - Sing a song(360p_H.264-AAC).mp3"

Then make the file executable
$ chmod +x
and run it
$ ./