Search code examples
bashshellmongoexport

Add a conditional SORT variable to mongoexport


I'm trying to set up a conditional --sort option in mongoexport but I'm having trouble with the string interpretation of my variable. Here is the code I'm trying to run :

#!/bin/bash
if [[ $IS_PROD == "true" ]]
then
   SORT='--sort "{_id : -1}"'
else
   SORT=""
fi

$MONGODB_HOME/bin/mongoexport \
--host=$HOST \
--port=$PORT \
--username=$USER \
--password=$PWD \
--db=$DB \
--limit=$LIMIT \
$SORT \
--collection=my_collection  | \
sed 's,\\,\\\\,g' \
> $TMP_FILE

While running this I get the following error error parsing command line options: invalid argument for flag '--sort' (expected string): invalid syntax

I've tried several quotes configuration and still couldn't make it work. Could someone please help me on this one?

Thanks


Solution

  • using bash array

    #!/bin/bash
    if [[ $IS_PROD == "true" ]]
    then
        SORT=(--sort "{_id : -1}")
    else
        SORT=()
    fi
    
    $MONGODB_HOME/bin/mongoexport \
    --host=$HOST \
    --port=$PORT \
    --username=$USER \
    --password=$PWD \
    --db=$DB \
    --limit=$LIMIT \
    "${SORT[@]}" \
    --collection=my_collection  | \
    sed 's,\\,\\\\,g' \
    > $TMP_FILE
    

    Explanation: using single quotes prevent shell expansions and double quotes are literal, but after variable expansion the double quotes are still litteral and expanded string is split by spaces.

    Otherwise to work around unbound variable bug

    #!/bin/bash
    
    options=(--host=$HOST \
    --port=$PORT \
    --username=$USER \
    --password=$PWD \
    --db=$DB \
    --limit=$LIMIT)
    if [[ $IS_PROD == "true" ]]
    then
        options+=(--sort "{_id : -1}")
    fi
    
    $MONGODB_HOME/bin/mongoexport \    
    "${options[@]}" \
    --collection=my_collection  | \
    sed 's,\\,\\\\,g' \
    > $TMP_FILE