Home > Net >  Loop, array, mysql, Bash, Linux
Loop, array, mysql, Bash, Linux

Time:07-09

I want to write a script that sends the select to the database

data_path="https://localhost/public/"
data_name=(PXL_20220628_152928222.mp4 PXL_20220628_163301667.mp4)
for q in "${data_name[@]}";
do
data_l=$(sudo mysql -h localhost -P 3306 -u ck****** -p"*******" -e "SELECT iddata FROM 
ck*****.data WHERE links = '$data_path$q'")
done
echo "$data_l"

In response I get only one record (id first file PXL_20220628_152928222.mp4 )

The loop is not working

CodePudding user response:

I copied your script to a file with a shebang, added an echo in front of the sudo to show the command being executed and moved the one AFTER the loop inside to show the result.

#! /bin/bash
data_path="https://localhost/public/"
data_name=(PXL_20220628_152928222.mp4 PXL_20220628_163301667.mp4)
for q in "${data_name[@]}"; do
    # data_l=$(sudo mysql -h localhost -P 3306 -u ck****** -p"*******" -e " SELECT iddata FROM ck*****.data WHERE links = '$data_path$q'
    data_l=$(echo "$q")
    echo "$data_l" # this was outside the loop
done
# echo "$data_l" # not here, this only reports the LAST value

Running it:

PXL_20220628_152928222.mp4
PXL_20220628_163301667.mp4

You were assigning it, but not reporting it, then overwriting with the second assignment, and only reporting that one after the loop was done.

Just move the echo at the end inside the loop.

  • Related