14.06.2014 Views

Unix Power Tools

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

36.21<br />

Logical operators<br />

Use these to compare two arguments. Depending on the values, the result<br />

written to standard output can be arg1 (or some portion of it), arg2, or0.<br />

The symbols | and & must be escaped.<br />

| Logical OR; if arg1 has a nonzero (and non-null) value, the output is<br />

arg1; otherwise, the output is arg2.<br />

& Logical AND; if both arg1 and arg2 have a nonzero (and non-null)<br />

value, the output is arg1; otherwise, the output is 0.<br />

: Sort of like grep (13.1); arg2 is a regular expression (32.4) to search for in<br />

arg1. If the arg2 pattern is enclosed in \( \), the output is the portion of<br />

arg1 that matches; otherwise, the output is simply the number of characters<br />

that match. Apattern match always applies to the beginning of<br />

the argument (the ^ symbol (32.5) is assumed by default).<br />

Examples<br />

Division happens first; output is 10:<br />

$ expr 5 + 10 / 2<br />

Addition happens first; output is 7 (truncated from 7.5):<br />

$ expr \( 5 + 10 \) / 2<br />

Add 1 to variable i; this is how variables are incremented in Bourne shell scripts:<br />

i=`expr "$i" + 1`<br />

Output 1 (true) if variable a is the string “hello”:<br />

$ expr "$a" = hello<br />

Output 1 (true) if variable b plus 5 equals 10 or more:<br />

$ expr "$b" + 5 \>= 10<br />

In the examples below, variable p is the string “version.100”. This command<br />

returns the number of characters in p:<br />

$ expr "$p" : '.*' Output is 11<br />

Match all characters and print them:<br />

$ expr "$p" : '\(.*\)' Output is “version.100”<br />

Output the number of lowercase letters matched:<br />

$ expr "$p" : '[a-z]*' Output is 7<br />

Match a string of lowercase letters:<br />

$ expr "$p" : '\([a-z]*\)' Output is “version”<br />

Chapter 36: Shell Programming for the Initiated 763<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2009 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!