繁体   English   中英

使用逗号分隔的bash变量运行for循环

[英]Run a for loop using a comma separated bash variable

我有一个集合列表作为Bash的逗号分隔变量,如下所示

list_collection=$collection_1,$collection_2,$collection_2,$collection_4

我想连接到Mongodb并在已完成的这些集合上运行一些命令,如下所示,但我无法使循环正常工作

${Mongo_Home}/mongo ${mongo_host}/${mongo_db} -u ${mongo_user} -p ${mongo_password} <<EOF 
use ${mongo_db};for i in ${list_collection//,/ } 
do 
  db.${i}.reIndex();
  db.${i}.createIndex({
  "recon_type":1.0,
  "account_name":1.0,
  "currency":1.0,
  "funds":1.0,
  "recon_status":1.0,
  "transaction_date":1.0},
  {name:"index_def"});
  if [ $? -ne 0 ] ; then 
    echo "Mongo Query to reindex ${i} failed" 
    exit 200 
  fi 
done
EOF

我在做什么错?

正确的方法是什么?

很难从一堆没有表现出这种行为的代码中猜测出您想要的行为是什么,但是要list_collection ,下面的代码将对list_collection每个项目运行一次mongo ,每次都使用一个不同的heredoc:

#!/usr/bin/env bash

# read your string into a single array
IFS=, read -r -a listItems <<<"$list_collection"

# iterate over items in that array
for i in "${listItems[@]}"; do
  { # this brace group lets the redirection apply to the whole complex command
    "${Mongo_Home}/mongo" "${mongo_host}/${mongo_db}" \
                          -u "${mongo_user}" -p "${mongo_password}" ||
      { echo "Mongo query to reindex $i failed" >&2; exit 200; } 
  } <<EOF
  use ${mongo_db}; 
  db.${i}.reIndex();
  db.${i}.createIndex({
    "recon_type":1.0,
    "account_name":1.0,
    "currency":1.0,
    "funds":1.0,
    "recon_status":1.0,
    "transaction_date":1.0
  }, {name:"index_def"});
EOF
done

或者,仅运行一次mongo (但是无法确定发生故障的索引)可能类似于:

#!/usr/bin/env bash

# read your string into a single array
IFS=, read -r -a listItems <<<"$list_collection"

buildMongoCommand() {
  printf '%s\n' "use $mongo_db;"
  for i in "${listItems[@]}"; do
    cat <<EOF
      db.${i}.reIndex();
      db.${i}.createIndex({
        "recon_type":1.0,
        "account_name":1.0,
        "currency":1.0,
        "funds":1.0,
        "recon_status":1.0,
        "transaction_date":1.0
      }, {name:"index_def"});
EOF
  done
}

"${Mongo_Home}/mongo" "${mongo_host}/${mongo_db}" \
    -u "${mongo_user}" -p "${mongo_password}" \
  < <(buildMongoCommand) \
  || { echo "Mongo query failed" >&2; exit 200; } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM