Issue
I have a SQLCMD in linux bash that im getting the results of a SELECT, how can i iterate over each line, and be able to pick out specific columns so that i can use them to run a bash command on
I currently doa SELECT and output to csv file, which works OK, but i would rather find a way that does not export, as permissions are in play, and i need to run all fully withing the one script
#!/bin/bash
sqlcmd -S DB_string -d DB -U USERNAME -P PASSWORD -Q \
"SET NOCOUNT ON SELECT * FROM dbo.microiopenvpn WHERE mode='create' ORDER BY id" -o "sqloutputCheckCreate.csv" -W -w 1024 -s"," -h-1
line_no=0
file=sqloutputCheckCreate.csv
line_no=$(awk '{x++} END {print x}' $file)
echo $line_no
#rowCount= sqloutputCheckCreate.csv | wc -l
if [ $line_no > 0 ]; then
echo "SQL Has Entries"
while IFS="," read -r d1 d2 d3 d4 d5 d6; do
if [ -e "/etc/openvpn/clients/$d6.ovpn" ]; then
echo "$d6 File exists"
sqlcmd -S DB_string -d DB -U USERNAME -P PASSWORD -Q \ -Q "SET NOCOUNT ON UPDATE dbo.microiopenvpn SET mode='valid' WHERE id='$d1'" < /dev$ echo "Database Updated - Successfully"
else
echo "$d6 does not exist - Action Creation Script of $d6"
./executecreate.sh
fi
done < sqloutputCheckCreate.csv
else
echo "Nothing there"
fi
cp /dev/null sqloutputCheckCreate.csv
the above works when exporting to external csav file, but I need to put sql export into variable and loop over that - so nothing external - ideas ?
Solution
Something like:
sqlcmd ... | while IFS="," read -r d1 d2 d3 d4 d5 d6
do
:# stuff
done
or, alternatively:
while IFS="," read -r d1 d2 d3 d4 d5 d6
do
:# stuff
done < <(sqlcmd ...)
Answered By - Roadowl