将 " 写入 bash 中的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2674427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:59:13  来源:igfitidea点击:

Writing " to a file in bash

bash

提问by S1syphus

Simply I need to write

只是我需要写

"echo" t${count} = "$"t${count}"

To a text file, including all the So the output would be something like:

到一个文本文件,包括所有的所以输出会是这样的:

echo "  t1  = $t1"

With " as they are. So I have tried:

使用 " 原样。所以我尝试过:

count=1
saveIFS="$IFS"
IFS=$'\n'
array=($(<TEST.txt))
IFS="$saveIFS"
for i in "${array[@]}"
do
echo "echo" t${count} = "$"t${count}""
(( count++ ))
done >> long1.txt

And variations on this such as:

以及对此的变化,例如:

echo "echo" """"" t${count} = "$"t${count}""

But I guess the wrapping in double " is only for variables.

但我想在 double " 中的包装仅适用于变量。

Ideas?

想法?

回答by falstro

There's actually no wrapping in double quotes for variables, first quote starts, the second quote ends the quoted string. You may however concatenate strings however you want, so "$"t${count}""will actually be equivalent to "$"t${count}, beginning with a quoted $-sign, followed by 't', followed by the count-variable.

变量实际上没有用双引号括起来,第一个引号开始,第二个引号结束引用的字符串。但是,您可以根据需要连接字符串,因此"$"t${count}""实际上等效于"$"t${count},以带引号的 $-sign 开头,后跟 't',然后是计数变量。

Back to your question, to get a ", you can either put it in a literal string (surrounded by single quotes), like so echo '"my string"', note though that variables are not substituted in literal strings. Or you can escape it, like so echo "\"my string\"", which will put a literal " in the string, and won't terminate it.

回到你的问题,要得到一个 ",你可以把它放在一个文字字符串中(用单引号括起来),就像这样echo '"my string"',注意虽然变量没有被替换为文字字符串。或者你可以像这样转义它echo "\"my string\"",其中将在字符串中放入一个文字 " ,并且不会终止它。

回答by ghostdog74

echo "echo \"t${count} = $t${count}\""

回答by Pasi Savolainen

You need to escape the doublequote (also dollar sign):

您需要转义双引号(也是美元符号):

echo "\" t = $t\""

回答by trfin

Yet another quoting variant (more of an exercise than a solution of course):

另一个引用变体(当然更多的是练习而不是解决方案):

# concatenate alternating single- & double-quoted blocks of substrings
count=1
echo 'echo "t'"${count}"' = $t'"${count}"'"'