1

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

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
1
  • Where is the problem? Commented May 19, 2014 at 17:05

2 Answers 2

1

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.

The simplest way of doing this might be a while read loop:

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

#!/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

1 Comment

This is a good suggestion as long as you don't change the value of N

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.