简体   繁体   中英

Run a for loop using a comma separated bash variable

I have a list of collections as a comma seperated variable in Bash like below

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

I want to connect to Mongodb and run some commands on these collections I have done like below but I am not getting the loop to work

${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

What wrong AM I doing?

What is the correct way?

It's hard to guess what your desired behavior is from a bunch of code that doesn't exhibit that behavior, but to take a shot at it, the following will run mongo once per item in list_collection , with a different heredoc each time:

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

Alternately, to run mongo just once (but lose the ability to tell which index a failure happened for) might look like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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