Using single quotes with echo in bash

2019-08-28 04:02发布

I am running some code from the command line by using echo and piping. This is the line of code I am trying to run:

echo 'import Cocoa;println("It's over there")' | xcrun swift -i -v -

I tried using a backslash to escape the single quote with a backslash like so:

echo 'import Cocoa;println("It\'s over there")' | xcrun swift -i -v -

That does not work.
I have seen other questions about using single quotes in bash but they seem to have the single quote as part of the script. In my case the single quote is part of some string that is being passed in from the echo. I don't really understand how to pass this particular string into bash without causing the following error:

/bin/sh: -c: line 0: unexpected EOF while looking for matching `"'
/bin/sh: -c: line 1: syntax error: unexpected end of file

This is probably very simple, and I am just being dumb but after searching for a while I cannot seem to figure out how to do this for my particular situation.

6条回答
Juvenile、少年°
2楼-- · 2019-08-28 04:42

try this:

echo -e 'Here you\x27re'

or

echo "Here you're"
查看更多
SAY GOODBYE
3楼-- · 2019-08-28 04:47

Since single-quotes can go "plainly" in double-quoted strings, I usually do something like this:

echo 'import Cocoa;println("It'"'"'s over there")' | xcrun swift -i -v -

I.e. end the single-quoted string, start a double-quoted string containing just a single-quote, end the double-quoted and start a new single-quoted.

查看更多
贪生不怕死
4楼-- · 2019-08-28 04:48

You can do:

echo 'import Cocoa;println("It'\''s over there")'

Which gives:

import Cocoa;println("It's over there")

Remember, in the bourne shell, echo will output the entire line, and a quote is just a "start interpreting this as literal" and "stop interpreting this as a literal" marker, which is slightly different from most programming languages.

Also see the POSIX spec of /bin/sh

查看更多
▲ chillily
5楼-- · 2019-08-28 04:49

Since no one else has mentioned it, you can use an ANSI-quoted string in bash, which can contain an escaped single quote. (Note the $ preceding the single-quoted string.)

echo $'import Cocoa;println("It\'s over there")' | xcrun swift -i -v -
查看更多
趁早两清
6楼-- · 2019-08-28 04:56

If you unsure about the quotes, just use the bash's heredoc feature:

cat <<'SWIFT' | xcrun swift -i -v -
import Cocoa;println("It's over there")
SWIFT

And if you use it unquoted e.g. SWIFT instead of 'SWIFT' you can use bash variables inside.

The best is use it as an function, like

getcode() {
cat <<SWIFT
import Cocoa;println("It's over there $1")
SWIFT
}

getcode "now" | xcrun swift -i -v -

will send to xcrun the text

import Cocoa;println("It's over there now")
查看更多
Ridiculous、
7楼-- · 2019-08-28 05:02

In BASH you cannot use nested single quote OR escape the single quote. But you can escape double quotes like this:

echo "import Cocoa;println(\"It's over there\")"
import Cocoa;println("It's over there")
查看更多
登录 后发表回答