Thursday, April 26, 2012

Linux/UNIX: Move File Starting With A Dash

In Unix or Linux operating systems, how do I move file(s) starting with a dash (e.g., /home/you/--filename.txt or /home/you/-filename.txt)?

Many meta-characters such as semicolons, spaces, backslashes, dollar signs, question marks, and asterisks are characters that are interpreted under Unix as commands. - or -- interpreted as an option passed to the command. Try the following suggestions for moving (mv) or copying (cp) these files.

Create Test File

Type the following command:
cd /tmp/
> '-foo.txt'
> '--bar.txt'

List Files Starting With a Dash

Try to list them, enter:
ls -l *.txt
You will get an error as follows:
ls: unrecognized option '--bar.txt'
Try `ls --help' for more information.
To delimit the option list use -- i.e. type the following command:
ls -l -- *.txt

cp and mv commands

Same can be used to copy or move files:
cp -- '--bar.txt' /path/to/dest
OR
cp -v -- '--bar.txt' /path/to/dest
To move files:
mv -- '--bar.txt' /path/to/dest
OR
mv -v -- '--bar.txt' /path/to/dest
In short the syntax is as follows:
cp options -- '--filename' /dest
mv options -- '--filename' /dest
The -- delimit the option list. Later arguments, if any, are treated a operands even if they begin with - or --. This applies to all commands such as rm, cp, mv, ls, ln and so on:
 command -- 'file'
command [options] -- 'file'
rm -- '--filename'
rm -fr -- '-dirname'
rmdir -- '--dirname'

No comments:

Post a Comment