如何迭代 bash sqlcmd 输出

How to iterate over bash sqlcmd output

我在 linux bash 中有一个 SQLCMD,我正在获取 SELECT 的结果,我如何遍历每一行,并能够挑选出特定的列,以便我可以用它们在

上运行一个bash命令

我目前做 SELECT 并输出到 csv 文件,工作正常,但我宁愿找到一种不导出的方式,因为权限正在发挥作用,我需要 运行完全使用同一个脚本

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

以上内容在导出到外部 csav 文件时有效,但我需要将 sql 导出到变量中并对其进行循环 - 所以没有外部 - 想法?

类似于:

sqlcmd ... | while IFS="," read -r d1 d2 d3 d4 d5 d6
do
    :# stuff
done

或者,或者:

while IFS="," read -r d1 d2 d3 d4 d5 d6
do
    :# stuff
done < <(sqlcmd ...)

将单列读入 Bash 循环

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

将多列读入 Bash 循环

$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