bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: basename, dirname why not built-in?


From: Chris F.A. Johnson
Subject: Re: basename, dirname why not built-in?
Date: Tue, 19 Feb 2002 21:37:34 GMT

On Mon, 18 Feb 2002, Andreas Schwab wrote:

> |> Both functions could be improved somewhat: I don't like the recursive
> |> calls to remove trailing slashes.
>
> What's wrong with loops?

Nothing. The revised functions should work in any POSIX shell and
conform to the specs:

        basename() {
            fn_path=$1
            fn_suffix=$2
            case $fn_path in
                "") return ;;
                *)  while [ "${fn_path#${fn_path%?}}" = "/" ]
                    do
                      fn_path=${fn_path%/}
                    done
                    case $fn_path in
                        "")  echo "/"; return ;;
                        *) fn_path=${fn_path##*/} ;;
                    esac
                    ;;
            esac
            if [ "$fn_path" = "$fn_suffix" ]
            then
                echo "$fn_path"
            else
                echo ${fn_path%$fn_suffix}
            fi
        }

        dirname () {
            fn_path=$1
            while [ "${fn_path%/}" != "$fn_path" ]
            do
              fn_path=${fn_path%/}
            done
            case $fn_path in
                "") echo '/' ;;
                */*) echo "${fn_path%/*}" ;;
                *) echo '.' ;;
            esac
        }

-- 
    Chris F.A. Johnson                        http://cfaj.freeshell.org
    ===================================================================
    My code (if any) in this post is copyright 2002, Chris F.A. Johnson
    and may be copied under the terms of the GNU General Public License



reply via email to

[Prev in Thread] Current Thread [Next in Thread]