basename with one argument fails with set -u
lunik1 opened this issue · 1 comments
lunik1 commented
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
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:-/}"
}