bash脚本中的循环不会捕获文件中的所有行

时间:2015-06-12 14:33:28

标签: mysql linux bash

我当前的代码是通过.csv文件,然后查询数据库以获取从角色和任务派生的信息。但是,脚本的这一部分只是读取.csv文件的第一行。有关如何读取.csv的多行的任何建议吗?

#!/bin/bash
> sql_stmnts.txt
> bad_info.txt

INPUT_FILE='test.csv'

IFS=','

while read f1 f2 f3 f4 f5 f6 f7; do

   #echo "f1='$f1', f2='$f2', f3='$f3', f4='$f4', f5='$f5', f6='$f6', f7='$f7'"

   user_id=$(echo "${f1//\"/}")
   first_name=$(echo "${f2//\"/}")
   last_name=$(echo "${f3//\"/}")
   title=$(echo "${f4//\"/}")
   requestor=$(echo "${f5//\"/}")
   request_email=$(echo "${f6//\"/}")
   roles=$(echo "$f7"| sed 's/"\(.[^"]*\)".*/\1/')
   tasks=$(echo "$f7"| sed 's/".[^"]*".*"\(.[^"]*\)"/\1/')

   roles=${roles//, /,}
   tasks=${tasks//, /,}

   for i in $roles
   do
       if sql_string=$(sshpass -p XXXXXX ssh jlefler@11.11.11.11 'mysql --skip-column-names -u root -pxxxxxx database -e "select id from roles where binary role_name='"'${i}';"'"'); then
          if [[ -n $sql_string ]]; then
             echo  "insert into user_roles (USER_ID, ROLE_ID, version) select id, $sql_string, 1 from users where user_id in ('$user_id');" >> sql_stmnts.txt
          else
             echo "$user_id - $i is a bad role" >> bad_info.txt
       fi
       else
          echo "Query Didn't Execute"
       fi
   done

   for i in $tasks
   do
       if sql_string=$(sshpass -p XXXXXXX ssh jlefler@11.11.11.11 'mysql --skip-column-names -u root -xxxxxxx database -e "select id from groups where binary group_name='"'${i}';"'"'); then
          if [[ -n $sql_string ]]; then
             echo  "insert into membership (USER_ID, group_ID, version) select id, $sql_string, 1 from users where user_id in ('$user_id');" >> sql_stmnts.txt
          else
             echo "$user_id - $i is a bad task" >> bad_info.txt
       fi
       else
          echo "Query Didn't Execute"
       fi
   done

done < $INPUT_FILE

使用bash -x选项运行时,会在第一行的末尾输出:

+ sql_string=3
+ [[ -n 3 ]]
+ echo 'insert into membership (USER_ID, group_ID, version) select id, 3, 1 from users where user_id in ('\''jlefler'\'');'
+ read f1 f2 f3 f4 f5 f6 f7

1 个答案:

答案 0 :(得分:0)

您可以使用for循环。我只是将sql_string设置为随机#。该示例仅显示您可以使用for循环来实现相同的目标。

对于前者: [c1 @ server CLI] $ cat 1.sh

#!/bin/bash

# Create fresh .txt files. You don't have to use the next 2 lines if you want them to be appended each time you run your script.
>a.txt
>b.txt

arr=("Case Manager" "Case Collector" "Engineer")
for line in "${arr[@]}"; do
      ##I'm just setting sql_string to a value. Set accordingly per your use.  
      if sql_string=$RANDOM ; then
         if [[ -n $sql_string ]]; then
            echo  $line - "$sql_string" >> a.txt
         else
            echo "No Data Found" >> b.txt
      fi
      else
         echo "Query Didn't Execute"
      fi
done

[c1 @ server CLI] $ cat a.txt

Case Manager - 13101
Case Collector - 3325
Engineer - 30248

[c1 @ server CLI] $