[Novalug] Shell Puzzle Challenge

Mike Miller mtmiller@ieee.org
Fri Mar 16 18:19:14 EDT 2012


On Fri, Mar 16, 2012 at 6:00 PM, James Ewing Cottrell 3rd
<JECottrell3@comcast.net> wrote:
> Since there seems to be an interest in Shell Scripting right now, I'd
> like to issue the following challenge:
>
> Write a shell function called "ispath" which returns true if its
> argument is part of $PATH, otherwise false

I'll humbly submit a solution adapted from my .profile, taken in turn
from Red Hat's default /etc/profile:

ispath() {
    echo "$PATH" | grep -E "(^|:)$1(\$|:)" > /dev/null 2>&1
}

Full disclosure, here's what I actually have in my .profile:

list_contains() {
    eval "echo \"\$$1\" | grep -E '(^|:)$2($|:)' > /dev/null 2>&1"
}

so I can reuse it like

if list_contains PATH "$dir"; then ...

or

if list_contains LD_LIBRARY_PATH "$dir"; then ...

You didn't mention bonus points for performance or fewest non-builtins
executed, I think I could come up with one that only uses shell
builtins.  Definitely interested in what others come up with.

-- 
mike



More information about the Novalug mailing list