When trying to cd
into a directory named "-2", the shell interprets the hyphen as a command option flag. This common issue occurs with any filename starting with special characters like hyphens.
Most shell users first try these approaches (which fail):
cd "-2"
cd '-2'
cd \-2
The shell still sees "-2" as an option rather than a directory name.
1. Using the -- Argument Separator
The most reliable solution is using --
to indicate end of options:
cd -- -2
2. Absolute Path Reference
You can bypass the issue by using the full path:
cd /path/to/-2
3. Relative Path with ./ Prefix
Add ./ to force interpretation as a filename:
cd ./-2
The double-dash (--
) is a POSIX standard way to mark the end of command options. The ./ prefix makes it clear this is a path reference rather than an option.
To avoid this problem when creating directories:
mkdir ./-2 # Instead of mkdir -2
mkdir -- -3 # Alternative creation method
The same techniques work for other problematic filenames:
cd -- "--option-looking-dir"
cd ./"(special$chars*)"
When you try to change into a directory that starts with a hyphen using the cd
command, you'll encounter an error like:
bash: cd: -2: invalid option
This happens because Unix/Linux commands interpret arguments starting with hyphens as command options rather than filenames or directory names.
You might have tried these common approaches without success:
cd "-2"
cd '-2'
cd \\-2
These methods typically work for special characters in filenames, but hyphens at the start of arguments are treated specially by most commands.
Method 1: Using the -- Argument
The most reliable solution is to use the --
argument separator:
cd -- -2
This tells the command to treat everything after --
as a filename, not an option.
Method 2: Using Absolute or Relative Path
You can also reference the directory through its path:
cd ./-2
Or with absolute path:
cd /path/to/your/-2
Method 3: Using find or ls with xargs
For more complex scenarios, you can use:
find . -name '-2' -type d -exec cd {} \\;
Or:
ls -d -- -2 | xargs cd
To avoid such problems when creating directories:
mkdir -- -2 # Correct way
mkdir ./-2 # Alternative
The --
convention is part of the POSIX standard and works with most Unix/Linux commands. It's particularly useful for:
- Filenames starting with hyphens
- Filenames that might be interpreted as options
- Scripts that need to handle arbitrary filenames