Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

expr

Evaluate expressions, evaluates an expression and writes the result on standard output. A blank line below separates increasing precedence groups.

Syntax
      expr expression
      expr option

Options:
   --help      Display help and exit
   --version   output version information and exit

Expressions:

   ARG1 | ARG2               ARG1 if it is neither null nor 0, otherwise ARG2 
   ARG1 & ARG2               ARG1 if neither argument is null or 0, otherwise 0 
   ARG1 < ARG2               ARG1 is less than ARG2 
   ARG1 <= ARG2              ARG1 is less than or equal to ARG2 
   ARG1 = ARG2               ARG1 is equal to ARG2 
   ARG1 != ARG2              ARG1 is unequal to ARG2 
   ARG1 >= ARG2              ARG1 is greater than or equal to ARG2 
   ARG1 > ARG2               ARG1 is greater than ARG2 
   ARG1 + ARG2               Arithmetic sum of ARG1 and ARG2 
   ARG1 - ARG2               Arithmetic difference of ARG1 and ARG2 
   ARG1 * ARG2               Arithmetic product of ARG1 and ARG2 
   ARG1 / ARG2               Arithmetic quotient of ARG1 divided by ARG2 
   ARG1 % ARG2               Arithmetic remainder of ARG1 divided by ARG2 
   STRING : REGEXP           Anchored pattern match of REGEXP in STRING 
   match STRING REGEXP       Same as STRING : REGEXP 
   substr STRING POS LENGTH  Substring of STRING, POS counted from 1 
   index STRING CHARS        Index in STRING where any CHARS is found, or 0 
   length STRING             Length of STRING 
   + TOKEN                   Interpret TOKEN as a string, even if it is a 
                             keyword like 'match' or an operator like '/'
   ( EXPRESSION )            Value of EXPRESSION

Beware that many operators need to be escaped or quoted for shells. Comparisons are arithmetic if both ARGs are numbers, else lexicographical. Pattern matches return the string matched between \( and \) or null; if \( and \) are not used, they return the number of characters matched or 0.

Exit status 
 0 if EXPRESSION is neither null nor 0,
 1 if EXPRESSION is null or 0,
 2 if EXPRESSION is syntactically invalid, 
 3 if an error occurred. 

Each token of the expression must be a separate argument.

Operands are either numbers or strings. `expr' coerces anything appearing in an operand position to an integer or a string depending on the operation being applied to it.

Strings are not quoted for `expr' itself, though you may need to quote them to protect characters with special meaning to the shell, e.g., spaces.

Operators may given as infix symbols or prefix keywords. Parentheses may be used for grouping in the usual manner (you must quote parentheses to avoid the shell evaluating them, however).
 

String expressions
------------------

`expr' supports pattern matching and other string operators. These have lower precedence than both the numeric and relational operators (in the next sections).
 

STRING : REGEX
     Perform pattern matching.  The arguments are coerced to strings
     and the second is considered to be a (basic, a la GNU `grep')
     regular expression, with a `^' implicitly prepended.  The first
     argument is then matched against this regular expression.

     If the match succeeds and REGEX uses `\(' and `\)', the `:'
     expression returns the part of STRING that matched the
     subexpression; otherwise, it returns the number of characters
     matched.

     If the match fails, the `:' operator returns the null string if
     `\(' and `\)' are used in REGEX, otherwise 0.

     Only the first `\( ... \)' pair is relevant to the return value;
     additional pairs are meaningful only for grouping the regular
     expression operators.

     In the regular expression, `\+', `\?', and `\|' are operators
     which respectively match one or more, zero or one, or separate
     alternatives.  SunOS and other `expr''s treat these as regular
     characters.  (POSIX allows either behavior.)

match STRING REGEX
     An alternative way to do pattern matching.  This is the same as
     STRING : REGEX.

substr STRING POSITION LENGTH
     Returns the substring of STRING beginning at POSITION with length
     at most LENGTH.  If either POSITION or LENGTH is negative, zero,
     or non-numeric, returns the null string.

index STRING CHARSET
     Returns the first position in STRING where the first character in
     CHARSET was found.  If no character in CHARSET is found in STRING,
     return 0.

length STRING
     Returns the length of STRING.

quote TOKEN
     Interpret TOKEN as a string, even if it is a keyword like MATCH or
     an operator like /.  This makes it possible to test `expr length
     quote "$x"' or `expr quote "$x" : '.*/\(.\)'' and have it do the
     right thing even if the value of $X happens to be (for example)
     `/' or `index'.  This operator is a GNU extension.  It is disabled
     when the environment variable `POSIXLY_CORRECT' is set.

To make `expr' interpret keywords as strings, you must use the
`quote' operator.

Numeric expressions
-------------------

`expr' supports the usual numeric operators, in order of increasing precedence. The string operators (previous section) have lower precedence, the connectives (next section) have higher.
 

+ -
     Addition and subtraction.  Both arguments are coerced to numbers;
     an error occurs if this cannot be done.

* / %
     Multiplication, division, remainder.  Both arguments are coerced to
     numbers; an error occurs if this cannot be done.

Relations for `expr'
--------------------

`expr' supports the usual logical connectives and relations. These are higher precedence than either the string or numeric operators (previous sections). Here is the list, lowest-precedence operator first.
 

 |   Returns its first argument if that is neither null nor 0,
     otherwise its second argument.

 &   Return its first argument if neither argument is null or 0,
     otherwise 0.

 < <= = == != >= >
     Compare the arguments and return 1 if the relation is true, 0
     otherwise.  `==' is a synonym for `='.  `expr' first tries to
     coerce both arguments to numbers and do a numeric comparison; if
     either coercion fails, it does a lexicographic comparison.

Examples
 

# A partial match will return the number of characters that match:
$ expr ss64 : ss6
3

# The condition in string 2 must entirely match string 1
$ expr ss64 : ss7
0

# Adding numbers
$ expr 5 + 2
7

# When multiplying the * has to be escaped
$ expr 5 \* 3
15

# Incrementing a variable (arithmetic expansion)
$ demo=1
$ demo=`expr $demo + 1`
$ echo $demo
2
$ demo=`expr $demo + 1`
$ echo $demo
3

# To print the non-directory part of the file name stored in `$fname',
  which need not contain a `/'.
$ expr $fname : '.*/\(^.*\)' '^|' $fname

$ expr abc : 'a\(.\)c'
b

$ expr index abcdef cz
3

$ expr index index a
expr: syntax error

$ expr index quote index a
0

"Silence is the perfect expression of scorn" ~ George Bernard Shaw (Back to Methuselah, 1921)


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

Recommended Links

Google matched content

Softpanorama Recommended

Top articles

Sites

Top articles

Sites

...



Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to to buy a cup of coffee for authors of this site

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: September, 04, 2019