【问题标题】:how to insert a row in table , mysql using bash - when $ is used?如何使用 bash 在表、mysql 中插入一行 - 使用 $ 时?
【发布时间】:2020-07-28 01:04:55
【问题描述】:

我正在尝试使用 bash 在 MySQL 表中插入一行,我已将以下脚本保存为 script.sh 并使用

运行

bash script.sh

当脚本执行时,它成功且没有错误,但包含加密值的密码字段('$2b$10$FywS3Lc27let0C9VVvZYFOBYg.AwGA3VEtUs5YIAjjUWSSEI3Fqt2')存储为其他值,例如

b0.AwGA3VEtUs5YIAjjUWSSEI3Fqt2

而不是

$2b$10$FywS3Lc27let0C9VVvZYFOBYg.AwGA3VEtUs5YIAjjUWSSEI3Fqt2

我尝试使用 '' 和 "" 和 `` ,它们都不起作用

那么当有 $ 值时如何插入呢?

#!/bin/bash
mysql <<EOF
GRANT ALL PRIVILEGES ON *.* TO "test_mysql_user"@"localhost" IDENTIFIED BY "test_password";

FLUSH PRIVILEGES;
create database cricket;
use cricket;

//created tables 
.....
.....

INSERT INTO admin
(
admin_id,
first_name,
middle_name,
last_name,
email_id,
password,
address,
city,
state,
zip_code,
country,
phone_code,
phone_number,
email_campaign)
VALUES
(
'root',
'root',
'root',
'root',
'root@gmail.com',
'$2b$10$FywS3Lc27let0C9VVvZYFOBYg.AwGA3VEtUs5YIAjjUWSSEI3Fqt2', //this field is the error , saved as someother value
'root',
'root',
'root',
'root',
'root',
'root',
'root',
'root');
EOF

【问题讨论】:

  • 考虑使用 source 命令。这可能是一个快速的解决方法。

标签: mysql linux bash shell


【解决方案1】:

如果您不想替换参数,则必须引用 'EOF' 字符串。

来自man bash | less +/"Here Documents"

这里的文档

这种类型的重定向指示 shell 从当前源读取输入,直到只包含单词的行 (没有尾随空格)可见。然后将所有读取到该点的行用作标准输入 命令。

here-documents的格式为:

<<[-]word
        here-document
delimiter

不会对 word 执行参数扩展、命令替换、算术扩展或路径名扩展。如果有的话 word 中的字符被引用,分隔符是 word 上去除引号的结果,以及 here-document 中的行 没有展开。 如果word不带引号,则here-document的所有行都进行参数扩展,命令 替换和算术扩展。在后一种情况下,字符序列 被忽略,并且 \ 必须 用于引用字符、$和`。

如果重定向操作符是

所以,当你引用 'EOF' 字符串时,你的脚本应该是这样的

mysql <<'EOF'
GRANT ALL PRIVILEGES ON *.* TO "test_mysql_user"@"localhost" IDENTIFIED BY "test_password";

FLUSH PRIVILEGES;
create database cricket;
use cricket;

//created tables 
.....
.....

INSERT INTO admin
(
admin_id,
first_name,
middle_name,
last_name,
email_id,
password,
address,
city,
state,
zip_code,
country,
phone_code,
phone_number,
email_campaign)
VALUES
(
'root',
'root',
'root',
'root',
'root@gmail.com',
'$2b$10$FywS3Lc27let0C9VVvZYFOBYg.AwGA3VEtUs5YIAjjUWSSEI3Fqt2', 
'root',
'root',
'root',
'root',
'root',
'root',
'root',
'root');
EOF

如果引用 word 对您来说不是一个选项,并且希望避免仅对加密密码字段进行参数替换,请将加密值存储在变量中并在文档中使用该变量。

password='$2b$10$FywS3Lc27let0C9VVvZYFOBYg.AwGA3VEtUs5YIAjjUWSSEI3Fqt2'

mysql <<EOF
INSERT INTO admin
(
admin_id,
first_name,
middle_name,
last_name,
email_id,
password,
address,
city,
state,
zip_code,
country,
phone_code,
phone_number,
email_campaign)
VALUES
(
'root',
'root',
'root',
'root',
'root@gmail.com',
'$password',
'root',
'root',
'root',
'root',
'root',
'root',
'root',
'root');
EOF

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多