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.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to learn the bash expr command inside and out. What are some of the most basic to the most creative/tricky/unexpected ways to use the expr command? Small, manageable examples are great.

share|improve this question

closed as not a real question by Gilles, enzotib, Michael Mrozek Dec 2 '11 at 20:27

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

I mostly used expr for its regular expression matching. It is sometimes more descriptive than sed or grep:

if expr "$value" : '.*bar$' >/dev/null; then ...

Compared to:

if echo "$value" | grep '.*bar$' >/dev/null; then ...


name=`expr "$filename" : '.*/\(.*\)\.[^.]*$'`

Compared to:

name=`echo "$filename" | sed 's!.*/\(.*\)\.[^.]*$/\1/'`

They are functionally equivalent, but expr was slightly faster. Especially in the older days when some shells had expr as a builtin (DEC Ultrix, for example).

Also, I program in strict Bourne shell syntax, so I still use expr for basic arithmatic, for example:

while [ $count -lt 10 ]; do
    # something
    count=`expr $count + 1`
share|improve this answer
not even POSIX sh? ouch. – jw013 Dec 1 '11 at 1:59
check some usage here ss64.com/bash/expr.html – Nikhil Mulley Dec 1 '11 at 5:46
As the question was tagged with bash, I would prefer if [[ "$value" =~ .*bar$ ]]; then instead your two if examples, and with [[ "$filename" =~ .*/(.*)\.[^.]*$ ]]; name="${BASH_REMATCH[1]}" the other two examples. – manatwork Dec 1 '11 at 14:55

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