Skip to content

Instantly share code, notes, and snippets.

@bdrewery
Created October 17, 2009 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdrewery/212376 to your computer and use it in GitHub Desktop.
Save bdrewery/212376 to your computer and use it in GitHub Desktop.
bash helper scripts, dirname/basename scripted is much much much quicker than forking a new process
# From Shell Scripting Recipes -Chris F.A. Johnson
split_line() {
local IFS=${DELIM:- }
local opts=$-
set -f
RET=( $* )
case $opts in
*f*) ;;
*) set +f ;;
esac
}
strip_trailing_slashes() {
_STRIP=$1
while :
do
case $_STRIP in
## If the last character is a slash, remove it
*/) _STRIP=${_STRIP%/} ;;
*) break ;;
esac
done
}
_basename() {
fn_path=$1
fn_suffix=$2
case $fn_path in
"") _BASENAME=; return ;;
*)
strip_trailing_slashes "$fn_path"
case $_STRIP in
"") fn_path="/" ;;
*) fn_path=${_STRIP##*/} ;;
esac
;;
esac
case $fn_path in
$fn_suffix | "/" ) _BASENAME="$fn_path" ;;
*) _BASENAME=${fn_path%$fn_suffix} ;;
esac
}
basename() {
_basename "$@" && echo $_BASENAME
}
_dirname() {
_DIRNAME=$1
strip_trailing_slashes "$_DIRNAME"
case $_STRIP in
"") _DIRNAME='/'; return ;;
*/*) _DIRNAME="${_STRIP%/*}" ;;
*) _DIRNAME='.'; return ;;
esac
strip_trailing_slashes "$_DIRNAME"
_DIRNAME=${_STRIP:-/}
}
dirname() {
_dirname "$@" && echo $_DIRNAME
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment