用户输入替换BASH中的变量

时间:2015-10-03 09:44:21

标签: regex bash sed

我希望有人可以帮助我进行一些文字操作,这不是我的强项,而是在尝试替换文件中的文字时遇到问题。

我有一个Terraform文件,我想要做的是运行一个BASH脚本,它收集用户输入并填写Terraform文件。格式如下:

Terraform.tf

throw

Provisioner.sh

variable "master_cpu" {default = }
variable "master_mem" {default = }
variable "master_count" {default = }
variable "master_template" {default = ""}
variable "master_datastore" {default = ""}
variable "master_secondary_disk_size" {default = }
variable "master_network_label" {default = ""}
variable "master_gateway" {default = ""}
variable "master_netmask" {default = ""}

这里有两个问题,第一个是数字不是用双引号括起来但文字是,所以只需在Terraform中搜索 default ="" 文件是没用的。

我遇到的另一个问题是变量没有扩展,例如:

echo -n "How many vCPU's should these VM's have? [ENTER]:"
read master_cpu
echo -n "How much RAM would you like to allocate? [ENTER]:"
read master_ram
echo -n "Template name? Format: Folder/template [ENTER]:"
read master_template
echo -n "Please provide the datastore name. [ENTER]:"
read master_dstore
...

将产生:default =" $ vc_address"而不是使用命令行上捕获的IP。

如果有人能给我一些关于如何在BASH中有效地做到这一点的指示,对于数字和文字,我真的很感激。

1 个答案:

答案 0 :(得分:1)

你想要的是一个模板引擎,这可以使用bash here-doc:

来实现
#!/bin/bash
echo -n "How many vCPU's should these VM's have? [ENTER]:"
read master_cpu
echo -n "How much RAM would you like to allocate? [ENTER]:"
read master_ram
echo -n "Template name? Format: Folder/template [ENTER]:"
read master_template
echo -n "Please provide the datastore name. [ENTER]:"
read master_dstore

# Use heredoc to generate the file, use EOF and not "EOF" since we want bash substitution
cat > Terraform.tf << EOF
variable "master_cpu" {default = $master_cpu}
variable "master_mem" {default = $master_ram}
variable "master_count" {default = }
variable "master_template" {default = ""}
variable "master_datastore" {default = ""}
variable "master_secondary_disk_size" {default = }
variable "master_network_label" {default = ""}
variable "master_gateway" {default = ""}
variable "master_netmask" {default = ""}
EOF

您可以在此处详细了解heredoc:http://tldp.org/LDP/abs/html/here-docs.html

对于不扩展的变量,bash中的'和'之间存在差异。基本上'表示文字(不扩展)。请参阅bash手册: