How do I escape a sub-directory name with an ampersand in it?

21,453

Solution 1

For the & (or almost any other character, you have two simple possibilities.

  • Put single quotes around the whole thing: ' -3ab_&_-3dc.img'
  • Put a backslash before each troublesome character: -3ab_\&_-3dc.img

There are two exceptions:

  • The single quote method doesn't work for a single quote. Backslash isn't special within single quotes, so you can't directly use that either. What you can do is end the single-quoted string, immediately use backslash plus single quote, and restart the single quote. So for example, if the name of the directory is foo'bar\qux: cd 'foo'\''bar\qux'. You can remember it that way: inside single quotes, '\'' gets you a single quote.
  • The backslash method doesn't work for newlines: backslash-newline is just ignored. You need to put single quotes around a newline.

You can use double quotes too, but then you need to put a backslash before some characters. Single quotes are more straightforward.

There's an additional difficulty here, which is that the name of the directory begins with a dash. That character tells the cd command (like almost every command) that an option follows. The dash is not special to the shell, only to the command, so quotes won't affect it. You have two ways of passing an argument that begins with a dash to a command without having it interpreted as an option:

  • Find another way to express this argument. For a file name, adding ./ in front still designates the same file.
  • Put the argument -- before. That tells the command to stop looking for options.

So here are some ways you can change into this subdirectory:

cd -- '-3ab_&_-3dc.img'
cd -- -3ab_\&_-3dc.img
cd ./-3ab_\&_-3dc.img
cd './-3ab_&_-3dc.img'

Solution 2

The ampersand does need to be escaped, but the problem you are having is likely with the leading -, rather than the ampersand. The leading - made cd think that you are passing in options. You can work around this by using ./:

cd './-3ab_&_-3dc.img'
Share:
21,453

Related videos on Youtube

WR7500
Author by

WR7500

Updated on September 18, 2022

Comments

  • WR7500
    WR7500 over 1 year

    Running a kornshell and trying to traverse a directory tree. Want to cd to a sub-directory named as follows:

     -3ab_&_-3dc.img
    

    My question is HOW do I need to escape the ampersand in this name? I've tried different combinations of double-quotes and backslashes without success.

  • phemmer
    phemmer about 11 years
    The & is definitely a problem. As for the -, it depends on the shell. Zsh is quite happy cding to a directory starting with a -. However bash is not.
  • WR7500
    WR7500 about 11 years
    Thanks. Thought I had tried that format too, but I forgot to escape the ampersand. When I did, it worked.
  • WR7500
    WR7500 about 11 years
    Thanks. Thought I had tried that format too, but I forgot to escape the ampersand (as in your 3rd example). When I did, it worked.