Last Updated: September 01, 2020
·
704
· Lars Van Casteren

Remote ssh cmd execution using typeset and variable substitution

Recently I had to execute a bunch of long somewhat complex bash code-snippets/functions together with some MongoDB queries on a remote host.
Using functions, substitution and typeset worked remarkably well for both the MongoDB queries and more complex bash code-snippets:

simple_mongodb_query(){
 /usr/bin/mongo --quiet -u $MONGO_USER --authenticationDatabase=admin -p $TARGET_DB_PASSWORD $TARGET_DB_HOSTNAME:27017/$DB --eval "
 db.order.find({
 '_id': '$ORDER_ID'
 })
 "
}

ORDER_ID=1

ssh -n $SSH_USER@$DB_HOSTNAME "$(typeset -f simple_mongodb_query); \
 MONGO_USER ="$MONGO_USER"; \
 TARGET_DB_PASSWORD ="$TARGET_DB_PASSWORD"; \
 TARGET_DB_HOSTNAME ="$TARGET_DB_HOSTNAME"; \
 DB=$DB; \
 ORDER_ID="$ORDER_ID" \
 simple_mongodb_query"`