Handling filenames starting with dashes

Recall that in any situation where a filename is stored in a variable, we must be careful when using it on a command line, because it might get interpreted as an option:

$ cp "$myvar" destdir

If myvar were a file named -alphabet-, this would result in a confusing error:

cp: invalid option -- 'h'

This is because the string was interpreted as a bundled set of options, and the letters a, l, and p are all valid options for the GNU cp command, but h is not.

We can address this one of two main ways; the first, for the commands that support it, is to use the -- terminator string option:

$ cp -- "$myvar" destdir

This signals to the cp command that every word after that argument is not an option, but (in this ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.