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 ?
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 ...)
Read Single Column into Bash Loop
SQLCMD="sqlcmd -h -1 -S $SERVERNAME -U $USERNAME -P $PASSWORD -d $DBNAME -Q"
for ctry in $($SQLCMD " SET NOCOUNT ON; SELECT ctry_cd FROM country ")
do
echo "Processing for Ctry: $ctry "
done
Read Multiple Columns into Bash Loop
$SQLCMD " SET NOCOUNT ON; SELECT ctry_cd, ctry_nm FROM country " | while read -r ctry_cd ctry_nm
do
echo "Processing for Ctry: $ctry_cd Name: $ctry_nm "
done
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.