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
The
./script
might be something along these lines:Drop the
echo
if you’re satisfied with the output.Run it as
Explanation:
<<< 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 toread
).-a collections
option ofread
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 arraycollections
prepended with the string--collections=
.See Shell Parameter Expansion (the section starting with ${parameter/pattern/string}) and Arrays.
You can split the array using IFS (Internal Field Separator), which uses space by default. Then you can loop the arguments in the array