dannyman.toldme.com


Technical

sh: “split” Shortcut

Recently, I wrote a shell script that had to break an IP address into octets. I wrote:


# octects
oct1=`echo $subnet | awk -F . '{print $1}'`
oct2=`echo $subnet | awk -F . '{print $2}'`
oct3=`echo $subnet | awk -F . '{print $3}'`
oct4=`echo $subnet | awk -F . '{print $4}'`

Later, when reviewing my script, Anonymous Coward offered this little gem:


$ set `echo 10.20.30.40 | tr '.' ' '`
$ echo $1
10
$ echo $2
20
$ echo $3
30
$ echo $4
40

Which means, you can just set a series of variables to $1, $2, $3, and so forth. In Anon’s example, the IP address is split into words with tr, and the variables set nice and easy with set.

Of course, if your script gets complex, you probably want to avoid relying on those variables. My original code could be re-expressed:


set `echo $subnet | tr '.' ' '`
oct1=$1; oct2=$2; oct3=$3; oct4=$4

Much nicer than invoking awk several times.

Read More

Next:
Previous:
Categories: Technical

Discover more from dannyman.toldme.com

Subscribe now to keep reading and get access to the full archive.

Continue reading