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 case) a file or directory name to operate on.

Unfortunately, while this is a very widespread convention, not every command supports these terminators. For such commands, a more general way to make this work is to specify the path in a form that doesn't start with a dash, whether by fully qualifying it from the filesystem root, or just by prefixing it with ./:

$ myscript /home/bashuser/-alphabet
$ myscript ./-alphabet

This also works fine in loops:

cd data || exit
for file in * ; do
    myscript ./"$file"
done
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.163.31