我有一个命令的“选项”数组。
my_array=(option1 option2 option3)
我想在 bash 脚本中调用此命令,使用数组中的值作为选项。所以,command $(some magic here with my_array) "$1"
变成:
command -option1 -option2 -option3 "$1"
我该怎么做?是否可以?
ベストアンサー1
我更喜欢一种简单的bash
方式:
command "${my_array[@]/#/-}" "$1"
原因之一是空间。例如,如果您有:
my_array=(option1 'option2 with space' option3)
基于的解决方案sed
会将其转换为-option1 -option2 -with -space -option3
(长度5),但上述bash
扩展会将其转换为-option1 -option2 with space -option3
(长度仍然为3)。很少,但有时这很重要,例如:
bash-4.2$ my_array=('Ffoo bar' 'vOFS=fiz baz')
bash-4.2$ echo 'one foo bar two foo bar three foo bar four' | awk "${my_array[@]/#/-}" '{print$2,$3}'
two fiz baz three