Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

basename with one argument fails with set -u #129

Open
lunik1 opened this issue Jul 3, 2022 · 1 comment
Open

basename with one argument fails with set -u #129

lunik1 opened this issue Jul 3, 2022 · 1 comment

Comments

@lunik1
Copy link

lunik1 commented Jul 3, 2022

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
Copy link

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants