Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using single quotes with echo in bash

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.

like image 717
Johnston Avatar asked Jan 18 '26 14:01

Johnston


1 Answers

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")
like image 71
jm666 Avatar answered Jan 21 '26 05:01

jm666



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!