下面是重現你的問題一個簡單的例子:
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
問題在哪裏? – rpax