Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

In a bash script, there are the following 2 lines:

ipaddr=$0
segments=`echo $ipaddr | cut --delimiter=. --fields=2-3 --output-delimiter=/`

I do not know how to interpret the second line where the variable $segments is created.

How does this part work?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

Here is the breakdown.

The echo will output whatever is in the variable $ipaddr

echo $ipaddr

This is then piped through to the following command.

Cut can be used to delimit (i.e. split into parts) a string. A parameter to cut tells it where to "cut" the string (here it is on points, so if the IP address is of the following format: "198.51.100.0", it will be split into 198 51 100 and 0). Another parameter tells it which parts, of the string that it has cut, it should take. Here it is parts 2 and 3. In the example ip I gave above, this would give 51 and 100. A final paramter tells it to put together the parts it has selected (parts 2 and 3) with a new delimiter (here a slash). The result would be 51/100.

cut --delimiter=. --fields=2-3 --output-delimiter=/

The result of all this (in my example being 51/100) is saved inside the segments variable. Whenever you run the following:

somevar=`somecommand`

whatever is between the backticks is executed. What it returns is passed to the left side of the equals sign.

share|improve this answer
    
$somevar=`somecommand` should not have a dollar sign in the LHS. I tried to edit the post but lack the privileges. –  tripleee Jan 24 '13 at 19:50

Let's dissect this.

echo $ipaddr

Assuming this is an IPv4 address written in decimal, this gives something like 100.90.80.70. This we pipe to

`cut --delimiter=. --fields=2-3 --output-delimiter=/

This will chop each of its input lines (just one in this case) at '.', so we now have 100 90 80 70. It selects fields 2 to 3 from here, i.e. we keep 90 80. This is written out, separated by '/'. Result is 90/80, as a rapid experiment shows.

The above mostly from looking at the manual page for cut(1), my memory isn't that good.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.