Arjun
Arjun

Reputation: 465

Single quote inside of double quoted string on linux command line

I have the following command

cmd '"asdf" "a'sdf"'

I need to surround the arguments with single quotes only. cmd doesnt work with double quotes for some reason I dont know. The above command doesnt work because the single in the middle terminates the first single quote. If I escape, to the following

cmd '"asdf" "a\'sdf"'

It still doesnt work. How do I get this working?

Upvotes: 3

Views: 5117

Answers (3)

ghoti
ghoti

Reputation: 46856

A long long time ago, a mentor suggested I use constructs like '"asdf" "a'"'"'sdf"'. It works, but it's bizarre to look at.

Since you can't put single quotes inside single quotes, escaping them like '"asdf" "a'\''sdf' may be the way to go.

Note that you can also use printf and variables interactively or within a shell script. With most shells (you haven't specified what you're using), you should get the similar results to this:

$ fmt='"asdf" "a%ssdf"\n'
$ printf "$fmt" "'"
"asdf" "a'sdf"
$ 

or you could even include the single quote using its ASCII value:

$ fmt='"asdf" "a\047sdf"\n'
$ printf "$fmt"
"asdf" "a'sdf"
$ 

or in csh:

% set fmt='"asdf" "a\047sdf"\n'
% printf "$fmt"
"asdf" "a'sdf"
%

This is shell-independent because if your shell doesn't have a printf command built in (as Bash has), then the command will most likely exist as a separate binary in /bin or /usr/bin.

I don't know your use case, so it's difficult to come up with a solution that I know will be applicable.

Upvotes: 1

Brōtsyorfuzthrāx
Brōtsyorfuzthrāx

Reputation: 4749

Well, you can always use autocomplete to help you find the answer.

For instance, if I have a file with an apostrophe in it, but I want to surround the path with single quotes, I can do this (using cat as an example command where the file is named sam's file.txt):

cat 'sam[press tab here]

and it autocompletes to this, for me:

cat 'sam'\''s\ file.txt

So, apparently it is possible. Another answerer mentioned the '\'' thing first, but I figured I'd tell you one way to try to figure it out if that's not working for you (and I thought I'd be another witness to tell you the other answer seems to work).

Upvotes: 0

Kevin
Kevin

Reputation: 56089

According to the bash man page:

   Enclosing  characters in single quotes preserves the literal value
   of each character within the quotes.  A single quote may not occur
   between single quotes, even when preceded by a backslash.

So the answer is, you can't include a single quote within a single-quoted string no matter how you try. But depending on how your script is set up you may be able to use '\'', which will end the first single quote, escape the second, and start another single-quoted string with the third.

Upvotes: 3

Related Questions