使用shell脚本将数据插入数据库,但在基础中获取空白值
我试图从中大量随机插入值。
#!/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
答案 0 :(得分:1)
这是一个更简单的例子,可以重现您的问题:
for el in foo bar
do
echo "$el"
done | head -n 1
echo "This is blank: $el"
这是因为for循环和你的mysql语句没有以任何方式连接。你必须从你的循环/管道获取数据到mysql。
最简单的方法可能是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
在您的示例中,这将是:
#!/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
更简单的方法是:
#!/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
答案 1 :(得分:0)
使用$(...)表示法封闭你的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