如何遍历bash sqlcmd输出

时间:2019-06-24 00:29:33

标签: linux bash sqlcmd

我在linux bash中有一个SQLCMD,它可以获取SELECT的结果,如何遍历每行,并能够挑选出特定的列,以便我可以使用它们在bash上运行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导出放入变量并对其进行循环-因此没有任何外部-想法?

1 个答案:

答案 0 :(得分:0)

类似的东西:

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 ...)