在 bash 脚本中使用 yaml

Using yaml in bash script

我有以下 yaml 文件,我需要在我的 bash 脚本中从这个 yaml 文件中获取输入

  Database: backup
  Table: mytable
  Partitions: P10,P11,P12

我试过如下,但出现错误

  #!/bin/bash
  Database=yq e '.Database' t_partitions.yaml
  Table=yq e '.Table' t_partitions.yaml
  Partitions=yq e '.Partitions' t_partitions.yaml
 
  mysql -u root -p -e "
  use $Database; 
  alter table $Table truncate partition $Partitions; 
  "

错误是

  bash m.sh run
  m.sh: line 2: e: command not found
  m.sh: line 3: e: command not found
  m.sh: line 4: e: command not found

你的赋值语句不符合Bash的语法。

你需要command substitution,喜欢:

#!/bin/bash
Database="$(yq e '.Database' t_partitions.yaml)"
Table="$(yq e '.Table' t_partitions.yaml)"
Partitions="$(yq e '.Partitions' t_partitions.yaml)"

mysql -u root -p -e "
use $Database; 
alter table $Table truncate partition $Partitions; 
"

使用$()获取命令的输出。使用 "" 以防止某些特殊字符在输出中最终断句。