Search code examples
mongodbbashshellmongodumpmongorestore

Unpack arguments into a command line flags using shell script


I am trying to create a shell script that will unpack multiple arguments and put them in a one-line with multiple flags

# How script will be run
./script "database" "collection1 collection2 collection3"
# Inside ./scipt
db=$1
collections=$2

mongodump --uri=<host:port> --db=${db} --collection=${for each argument in collections variable}

# Output should be this:
mongodump --uri=<host:port> --db=${db} --collection=collection1 --collection=collection2 --collection=collection3

The problem is how to unpack the ${collections} variable which takes space-separated arguments into an array or something and calls each collection together with the --collection flag in one line


Solution

  • The ./script might be something along these lines:

    #!/bin/bash
    
    db=$1
    read -ra collections <<< "$2"
    
    echo mongodump --uri=host:port --db="$db" "${collections[@]/#/--collections=}"
    

    Drop the echo if you're satisfied with the output. Run it as

    ./script "database" "collection1 collection2 collection3"
    

    Explanation:

    • The <<< string construct is called here string. The value of the string after expansions is supplied to the command on its standard input (See Here Strings). Here strings can be used in any command (They are not special to read).
    • The -a collections option of read means that the words of the input are assigned to sequential indices of the array variable collections (any valid variable name could be used).
      See read Bash Builtin.
    • "${collections[@]/#/--collections=}" constructs a list whose each item is the consecutive element of the array collections prepended with the string --collections=.
      See Shell Parameter Expansion (the section starting with ${parameter/pattern/string}) and Arrays.