Reject a leading dash in user input
Reject a value that starts with a dash before passing it on, using case $x in -*). It is the fallback for tools that do not accept a double dash.
A function takes a file name from its caller, and a value such as -rf must not reach the program that gets it.
safe_name() {
case $1 in
-*) echo "refused: $1 starts with a dash" >&2; return 1 ;;
'') echo "refused: empty" >&2; return 1 ;;
esac
printf 'ok: %s\n' "$1"
}
safe_name report.txt
safe_name -rf
safe_name ""
safe_name ./-rfok: report.txt
refused: -rf starts with a dash
refused: empty
ok: ./-rfThe case pattern -* matches any value that begins with a hyphen, so the function refuses it before the value reaches a command. The same check is spelled [[ $1 == -* ]] in Bash, and the case form works in any POSIX shell, as defined in the shell command language. The fourth call shows the escape hatch: a relative path with ./ in front is accepted, because it cannot be an option.
Rejecting is a policy, so the caller loses the ability to use a file that really starts with a dash. Prefer -- where the tool supports it and keep this check for the tools that do not. A check on the first character does nothing about other dangers in a name, like a newline or .. components.