skip to Main Content

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

2

Answers


  1. 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.
    Login or Signup to reply.
  2. You can split the array using IFS (Internal Field Separator), which uses space by default. Then you can loop the arguments in the array

    #!/bin/bash
    
    db=$1
    collections=($2)
    
    mongodump --uri=<host:port> --db=${db} "${collections[@]/#/--collection=}"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search