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

时间:2019-01-31 20:56:22

标签: mongodb bash for-loop

我在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

我在做什么错?

正确的方法是什么?

1 个答案:

答案 0 :(得分:2)

很难通过一堆没有表现出这种行为的代码来猜测您的期望行为是什么,但是要尝试一下,下面的代码将运行mongo list_collection中的每个项目,每次都使用不同的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; }