首页 > 解决方案 > 在 bash 脚本中创建 SQL 脚本

问题描述

我正在尝试使用基本的 bash 脚本引导 mysql

cat <<EoF > /tmp/mysql-load-table.sql
CREATE DATABASE  IF NOT EXISTS `web_customer_tracker`;
USE `web_customer_tracker`;

DROP TABLE IF EXISTS `customer`;

CREATE TABLE `customer` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(45) DEFAULT NULL,
  `last_name` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;

LOCK TABLES `customer` WRITE;

INSERT INTO `customer` VALUES 
    (1,'JeanLuc','Picard','picard@tng.com'),
    (2,'William','Riker','riker@tng.com'),
    (3,'Beverly','Crusher','crusher@tng.com'),
    (4,'Geordi','LaForge','laforge@tng.com'),
    (5,'Data','Android','data@tng.com');

UNLOCK TABLES;
EoF

如果我将这些命令直接输入到 MySQL 中,上述工作正常,但是当我将其作为 bash 脚本的一部分运行时,我得到以下错误

-bash: web_customer_tracker: command not found
-bash: web_customer_tracker: command not found
-bash: customer: command not found
-bash: customer: command not found
-bash: customer: command not found
-bash: first_name: command not found
-bash: last_name: command not found
-bash: email: command not found
-bash: customer: command not found
-bash: customer: command not found
-bash: customer: command not found

无法弄清楚我在这里缺少什么,任何帮助将不胜感激。我想将其创建为 SQL 脚本,然后将其传递给 mysql 以创建数据库并加载数据。

标签: mysqllinuxbashshell

解决方案


引用您的 heredoc 分隔符,例如

cat <<'EoF' > /tmp/mysql-load-table.sql
CREATE DATABASE  IF NOT EXISTS `web_customer_tracker`;
USE `web_customer_tracker`;
...
EoF

man bash

不会对 word 执行参数和变量扩展、命令替换、算术扩展或路径名扩展。如果 word 中的任何字符被引用,则分隔符是 word 上去除引号的结果,并且 here-document 中的行不展开。 如果 word 不被引用,则 here-document 的所有行都经过参数扩展、命令替换和算术扩展,字符序列 <newline> 被忽略,并且必须使用 \ 来引用字符、$ 和 `。


推荐阅读