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)? How do I copy a file whose name begins with dash/hyphen (“-“)?

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

Move File Starting With A Dash

The syntax is as follows:

cp -- source dest
cp [option] -- source dest

We use “--” to make Linux and Unix command stop parsing shell command line options. Now, let us see some examples.

Create a 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 ls command:

ls -l -- *.txt

The cp and mv commands

When a file whose name begins with - or --, copy or move files using the following syntax:

cp -- '--bar.txt' /path/to/dest
cp -- '-test.doc' /home/vivek/backups/test.doc

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

Unix and Linux copy file starting with a dash

The - or -- considered as part of command line options. Therefore, you can not copy, list, delete or move any files starting with those characters. 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 Linux/Unix/macOS/*BSD commands such as rm, cp, mv, ls, ln and so on:

 command -- 'file'
command [options] -- 'file'
rm -- '--filename'
rm -fr -- '-dirname'
rmdir -- '--dirname'

Tip: Handling a filename starting with a dash (-)

You can “hide” the dash from the command by starting the filename with ./ (dot slash). For example, try to remove a file named “-filename.txt” using rm command:

> '-filename'
rm -filename # will get an error #
rm ./-filename

Conclusion

This page explained how to handle a Linux or Unix filename starting with a dash (-). The trick is to either start the filename with ./ or pass the -- before filename.

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.