[英]Unpack arguments into a command line flags using shell script
我正在尝试创建一个 shell 脚本,它将解压缩多个 arguments 并将它们放在具有多个标志的一行中
# 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
问题是如何解包${collections}
变量,它将空格分隔的 arguments 放入一个数组或其他东西中,并在一行中将每个集合与--collection
标志一起调用
./script
可能是这样的:
#!/bin/bash
db=$1
read -ra collections <<< "$2"
echo mongodump --uri=host:port --db="$db" "${collections[@]/#/--collections=}"
如果您对 output 感到满意,请放弃echo
。 运行它
./script "database" "collection1 collection2 collection3"
您可以使用默认使用空间的 IFS(内部字段分隔符)拆分数组。 然后可以循环数组中的arguments
#!/bin/bash
db=$1
collections=($2)
mongodump --uri=<host:port> --db=${db} "${collections[@]/#/--collection=}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.