pure-bash-bible icon indicating copy to clipboard operation
pure-bash-bible copied to clipboard

basename with one argument fails with set -u

Open lunik1 opened this issue 2 years ago • 1 comments

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

lunik1 avatar Jul 03 '22 23:07 lunik1

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:-/}"
}

sensemon-san avatar Apr 26 '23 12:04 sensemon-san