使用 bash 将变量写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35333077/
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
Writing variables to file with bash
提问by S4M11R
I'm trying to configure a file with a bash script. And the variables in the bash script are not written in file as it is written in script.
我正在尝试使用 bash 脚本配置文件。并且bash脚本中的变量并没有像在脚本中那样写在文件中。
Ex:
前任:
#!/bin/bash
printf "%s" "template("$DATE\t$HOST\t$PRIORITY\t$MSG\n")" >> /file.txt
exit 0
This results to template('tttn') instead of template("$DATE\t$HOST\t$PRIORITY\t$MSG\n in file.
这导致 template('tttn') 而不是 template("$DATE\t$HOST\t$PRIORITY\t$MSG\n in file.
How do I write in the script so that the result is template("$DATE\t$HOST\t$PRIORITY\t$MSG\n in the configured file?
我如何在脚本中编写,以便结果为模板(配置文件中的“$DATE\t$HOST\t$PRIORITY\t$MSG\n?
Is it possible to write variable as it looks in script to file?
是否可以将在脚本中查找的变量写入文件?
回答by Didier Trosset
Enclose the strings you want to write within single quotes to avoid variable replacement.
将要写入的字符串括在单引号内以避免变量替换。
> FOO=bar
> echo "$FOO"
bar
> echo '$FOO'
$FOO
>
回答by hgiesel
Using printf
in any shell script is uncommon, just use echo
with the -e
option.
It allows you to use ANSI C metacharacters, like \t
or \n
. The \n
at the end however isn't necessary, as echo
will add one itself.
使用printf
任何shell脚本是少见,只是使用echo
与-e
选项。它允许您使用 ANSI C 元字符,例如\t
或\n
。将\n
在年底却是没有必要的,因为echo
会增加一个本身。
echo -e "template(${DATE}\t${HOST}\t${PRIORITY}\t${MSG})" >> file.txt
The problem with what you've written is, that ANSI C metacharacters, like \t
can only be used in the firstparameter to printf
.
你所写的问题是,ANSI C 元字符,比如\t
只能用在第一个参数中printf
。
So it would have to be something like:
所以它必须是这样的:
printf 'template(%s\t%s\t%s\t%s)\n' ${DATE} ${HOST} ${PRIORITY} ${MSG} >> file.txt
But I hope we both agree, that this is very hard on the eyes.
但我希望我们都同意,这对眼睛来说很难。