How to echo a string that contains quotes without modifying the contents of the string?

StackOverflow https://stackoverflow.com/questions/23600255

  •  20-07-2023
  •  | 
  •  

質問

I wish to echo a string that contains quotes and new line characters, such as " "What do we say to the God of Death?\nNot today." "

echo -e " "What do we say to the God of Death?\nNot today." " 

Won't work, of course.

What could I do, other than adding /s to the inside quotes, to have an output showing this:

"What do we say to the God of Death?
Not today." 

Thanks!

役に立ちましたか?

解決

You cannot enclose the same set of quotes within a pair of quotes without escaping.

The simplest option is to make use of ANSI-C quoting:

 echo -e $'"What do we say to the God of Death?\nNot today."'

It'd produce:

"What do we say to the God of Death?
Not today."

If you wanted to use only double quotes, then you'd need to escape the ones that you need to print:

echo -e "\"What do we say to the God of Death?\nNot today.\""

他のヒント

Try this,

echo -e '"What do we say to the God of Death?'"\n"'Not today."'

Example:

$ echo -e '"What do we say to the God of Death?'"\n"'Not today."'
"What do we say to the God of Death?
Not today."

The strings enclosed within single quotes are won't get parsed in echo command.So this "What do we say to the God of Death? won't get parsed. And the strings enclosed within double quotes would be parsed. So this \n get parsed.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top