3

I have a bash variable $i which has to be embed in mongo shell query to get the data by comparing date.

i=10
while [  "$i" -lt 12 ]; do
        mongo $MONGO_DATABASE --eval 'printjson(db.mycollection.find({"created_at":{"$lte":ISODate(2016-04-\"$i\"T09:26:31.190Z)}}).toArray())' > $OUTPUT_DIRECTORY/$FILE_NAME  
done

The above implementation is giving i: command not found

1 Answer 1

1

Shell variables aren't expanded within single quotes. Use double quotes:

mongo "$MONGO_DATABASE" --eval "printjson...ISODate(2016-04-${i}T09:26:31.190Z)

You will then need to escape your usages of double quotes within the string that you are evaluating, e.g. \"created_at\". You will also need to escape other usages of $, e.g. \$lte.

Alternatively, you can use single quotes around the whole command and then use something like this:

mongo "$MONGO_DATABASE" --eval 'printjson...ISODate(2016-04-'"$i"'T09:26:31.190Z)

i.e. close the single quotes, concatenate the shell variable (inside double quotes), then reopen the single quotes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.