Home > Software design >  Unpack arguments into a command line flags using shell script
Unpack arguments into a command line flags using shell script

Time:08-18

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

CodePudding user response:

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"

CodePudding user response:

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=}"
  • Related