Shell script functions to replace basename and dirname
When writing shell-scripts, it is quite common to use the
basename and dirname. Since they are typically provided as shell scripts under /usr/bin/, I wrote my own set of the as Bash functions instead. Feel free to use them as you see fit.
function basename () {
if [ $# -lt 1 ]; then
echo "Usage: $0 [ ]" 1>&2
return 1
else
local -r sfx=${2-''}
local -r trim=${1%/}
local -r fname=${trim##*/}
echo ${fname%%$sfx}
return 0
fi
}
function dirname () {
if [ $# -lt 1 ]; then
echo "Usage: $0 " 1>&2
return 1
else
local -r fname=${1%/?*}
if [ "x$fname" = "x$1" ]; then
echo "."
else
echo $fname
fi
return 0
fi
}

0 Comments:
Post a Comment
<< Home