10

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.

2 Answers 2

14

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'
1
  • 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.
    – RCinICT
    Commented Mar 26, 2013 at 0:02
6

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'
2
  • 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.
    – phemmer
    Commented Mar 25, 2013 at 23:52
  • Thanks. Thought I had tried that format too, but I forgot to escape the ampersand. When I did, it worked.
    – RCinICT
    Commented Mar 26, 2013 at 0:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .