bash 使用shell脚本将数据插入数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23742963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:29:27  来源:igfitidea点击:

Using shell script to insert data into database

mysqlbashshell

提问by Junior_jr

Using shell script to insert data into database, but getting a blank value in the base

使用shell脚本将数据插入数据库,但在基数中得到一个空值

Im trying to make massive and randomly insert values from it.

我试图从中制作大量随机插入的值。

#!/bin/bash
N=1
ARRAY=( adssa asdsa fdgfd vcbxcxv )
for el in "${ARRAY[@]}"
do echo $el
done | shuf | head -$N

mysql -u root -pPass somebase << EOF
INSERT INTO sometable (name) VALUES ('$el');
SELECT * FROM site_user;
EOF

回答by that other guy

Here's a simpler example that reproduces your problem:

这是一个更简单的示例,可以重现您的问题:

for el in foo bar
do
  echo "$el"
done | head -n 1

echo "This is blank: $el"

This happens because the for loop and your mysql statement are not connected in any way. You have to get the data from your loop/pipeline to mysql.

发生这种情况是因为 for 循环和您的 mysql 语句没有以任何方式连接。您必须将数据从循环/管道获取到 mysql。

The simplest way of doing this might be a while readloop:

执行此操作的最简单方法可能是while read循环:

for el in foo bar
do
  echo "$el"
done | head -n 1 | while read -r line
   do
      echo "This is not blank: $line"
   done

In your example, this would be:

在您的示例中,这将是:

#!/bin/bash
N=1
ARRAY=( adssa asdsa fdgfd vcbxcxv )
for el in "${ARRAY[@]}"
do echo $el
done | shuf | head -$N | while read -r line
do 
mysql -u root -pPass somebase << EOF
  INSERT INTO sometable (name) VALUES ('$line');
  SELECT * FROM site_user;
EOF
done

The simpler way would be:

更简单的方法是:

#!/bin/bash
n=1
array=( adssa asdsa fdgfd vcbxcxv )
printf "INSERT INTO sometable (name) VALUES ('%s');\n" "${array[@]}" | \
  shuf | head -n $n | mysql -u root -pPass somebase

回答by Jonathan Wheeler

Enclose your for loop using $(...) notation to get your output into the elvariable.

使用 $(...) 符号将您的 for 循环括起来,以将您的输出放入el变量中。

#!/bin/bash
N=1
ARRAY=( adssa asdsa fdgfd vcbxcxv )
el=$(for el in "${ARRAY[@]}"
do echo $el
done | shuf | head -$N)

mysql -u root -p1550005 stat << EOF
INSERT INTO site_user (name) VALUES ('$el');
SELECT * FROM site_user;
EOF