First of all, always enclose your variable between double quotes (there are exceptions to this rule, but you will easily recognize them when the moment comes). The risk that your filename contains space characters is equally high (and probably higher) than a filename that begins with a minus sign.
Your first command should thus be:
<command> "$FILENAME"
Next, the -<option>
case. You sum up the issue quite well: using --
is OK but you cannot blindly add --
to your command as all commands do not support this syntax.
A perfectly safe way to protect against variables that contain a filename starting with a minus sign (or any other sensitive character) is to change the filename in order to prepend a path to it, either a relative path (./file
) or an absolute path (/foo/bar/file
). That way, the first char is harmless since it is either .
or /
.
This code will add a relative path to $filename
unless it is already an absolute path:
[[ "$filename" != /* ]] && filename="./$filename"
Personally, in my shell scripts, I prefer to change file arguments to their canonical representation (full path):
filename="$(readlink -f -- "$filename")"
or:
filename="$(realpath -m -- "$filename")"
(if you wonder which among realpath
and readlink
you should use, see this excellent answer)