On Mon, Jun 03, 2002, Nadav Har'El wrote about "Re: small and extremely annoying 
question":
> $ dirname /usr/local/bin/gcc
> /usr/local/bin
> 
> (or if you're into S&M, you can do the same with the more generic but
> complicated expr tool. Shells like zsh or bash also have builtin features
> that let you do such substitutions).

I figured that since I came out the total idiot (giving the 4th identical
answer in 5 minutes), I'll expand your knowledge by showing *how* this
can be done with expr(1) and using shell builtin features.

expr(1), which I guess most people won't be very familar with, was Unix's
original "bag of tricks", that did things that nowadays are usually either
done in the shell (like incrementing a counter, cutting of parts of
strings) or with specialized utilities like the aforementioned dirname.

For example, to cut off the dirname, one could use

$ expr /usr/local/bin/gcc : '\(.*\)/[^/]*'
/usr/local/bin

What this scary thing (hence the reference to S&M :) ) says is roughly
this: take the first string (/usr/local/bin/gcc) and look for "something"
followed by a slash and then only non-slash characters. Then output that
"something".

A real implementation of dirname in terms of expr can be even uglier: see
if you can understand the following (straight out of Solaris's /bin/dirname):
        exec /usr/bin/expr \
                "${1:-.}/" : '\(/\)/*[^/]*//*$'  \| \
                "${1:-.}/" : '\(.*[^/]\)//*[^/][^/]*//*$' \| \
        .

expr's other most common use was to add numeric loop to shell scripts, in
which you need to increment your counter variable:

$ expr 7 + 1
8

Nowadays, with more advanced shells like bash and zsh, one would normally
use the shell's builtin features instead of expr. For example (in bash):

$ echo $((7+1))
8
$ let i=7; let i++; echo $i
8

and for the dirname thing:

$ FILE=/usr/local/bin/gcc
$ echo ${FILE%/*}
/usr/local/bin



-- 
Nadav Har'El                        |        Monday, Jun 3 2002, 23 Sivan 5762
[EMAIL PROTECTED]             |-----------------------------------------
Phone: +972-53-245868, ICQ 13349191 |Open your arms to change, but don't let
http://nadav.harel.org.il           |go of your values.

=================================================================
To unsubscribe, send mail to [EMAIL PROTECTED] with
the word "unsubscribe" in the message body, e.g., run the command
echo unsubscribe | mail [EMAIL PROTECTED]

Reply via email to