简体   繁体   English

Bash脚本变量解释

[英]Bash script variable interpretation

I have a text file that contains references to variables and lets a user set up the formatting they want around variables, say something like 我有一个文本文件,其中包含对变量的引用,并允许用户设置他们想要的变量格式,比如说

 The date is $DATE
 The time is $TIME

I then want to read this text file in, replace the variables, and print the result to stdout using a bash script. 然后我想读取这个文本文件,替换变量,并使用bash脚本将结果打印到stdout。 The closest thing I've gotten is using "echo" to output it, 我得到的最接近的是使用“echo”来输出它,

 DATE="1/1/2010"
 TIME="12:00"
 TMP=`cat file.txt`
 echo $TMP

However, the output ends up all on one line, and I don't want to have \\n at the end of every line in the text file. 但是,输出最终都在一行上,我不希望在文本文件的每一行的末尾都有\\ n。 I tried using "cat << $TMP", but then there are no newlines and the variables inside the text aren't getting replaced with values. 我尝试使用“cat << $ TMP”,但之后没有新行,文本中的变量也没有被值替换。

You can use eval to ensure that variables are expanded in your data file: 您可以使用eval确保在数据文件中扩展变量:

DATE="1/1/2010"
TIME="12:00"
while read line
do
  eval echo ${line}
done < file.txt

Note that this allows the user with control over the file content to execute arbitrary commands. 请注意,这允许用户控制文件内容以执行任意命令。

If the input file is outside your control, a much safer solution would be: 如果输入文件不在您的控制之下,那么更安全的解决方案是:

DATE="1/1/2010"
TIME="12:00"
sed -e "s#\$DATE#$DATE#" -e "s#\$TIME#$TIME#" < file.txt

It assumes that neither $DATE nor $TIME contain the # character and that no other variables should be expanded. 它假定$DATE$TIME都不包含#字符,并且不应扩展其他变量。

Slightly more compact than Adam's response: 比亚当的反应稍微紧凑:

DATE="1/1/2010"
TIME="12:00"
TMP=`cat file.txt`
eval echo \""$TMP"\"

The downside to all of this is that you end up squashing quotes. 所有这一切的缺点是你最终挤压报价。 Better is to use a real template. 更好的是使用真实的模板。 I'm not sure how to do that in shell, so I'd use another language if at all possible. 我不确定如何在shell中执行此操作,因此如果可能的话,我会使用其他语言。 The plus side to templating is that you can eliminate that "arbitrary command" hole that Adam mentions, without writing code quite as ugly as sed. 模板的好处在于你可以消除Adam提到的那个“任意命令”漏洞,而不用像sed那样编写丑陋的代码。

Just quote your variable to preserve newline characters. 只需引用您的变量以保留换行符。

DATE="1/1/2010"
TIME="12:00"
TMP=$(cat file.txt)
echo "$TMP"

For your modification of values in file with variables you can do - 您可以使用变量修改文件中的值 -

while read -r line
do 
   sed -e "s@\$DATE@$DATE@" -e "s@\$TIME@$TIME@" <<< "$line"
done < file.txt

Test: 测试:

[jaypal:~/Temp] cat file.txt
The date is $DATE
The time is $TIME
[jaypal:~/Temp] DATE="1/1/2010"
[jaypal:~/Temp] TIME="12:00"
[jaypal:~/Temp] while read -r line; do sed -e "s@\$DATE@$DATE@" -e "s@\$TIME@$TIME@" <<< "$line"; done < file.txt
The date is 1/1/2010
The time is 12:00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM