dylanaraps / pure-bash-bible

📖 A collection of pure bash alternatives to external processes.
MIT License
36.59k stars 3.29k forks source link

basename with one argument fails with set -u #129

Open lunik1 opened 2 years ago

lunik1 commented 2 years ago

As the second argument can be unbound in basename, the following script will fail:

#!/usr/bin/env bash

set -u

basename() {
    # Usage: basename "path" ["suffix"]
    local tmp

    tmp=${1%"${1##*[!/]}"}
    tmp=${tmp##*/}
    tmp=${tmp%"${2/"$tmp"}"}

    printf '%s\n' "${tmp:-/}"
}

basename ~/Pictures/Wallpapers/1.jpg

with

./basename.sh: line 11: 2: unbound variable
sensemon-san commented 1 year ago

Fixed:

basename() {
    # Usage: basename "path" ["suffix"]
    local tmp

    case "${1:-''}" in '') return 1;; esac
    tmp=${1%"${1##*[!/]}"}
    tmp=${tmp##*/}
    case "${2:-''}" in '') :;; *) tmp=${tmp%"${2/"$tmp"}"};; esac

    printf '%s\n' "${tmp:-/}"
}