Skip to main content
corrected minor grammar
Source Link
manatwork
  • 32.1k
  • 8
  • 104
  • 93

I would prefer a plain bash way:

command "${my_array[@]/#/-}" "$1"

One reason for this is are the spaces. For example if you have:

my_array=(option1 'option2 with space' option3)

The sed based solutions will transform it in -option1 -option2 -with -space -option3 (length 5), but the above bash expansion will transform it into -option1 -option2 with space -option3 (length still 3). Rarely, but sometimes this is important, for example:

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

I would prefer a plain bash way:

command "${my_array[@]/#/-}" "$1"

One reason for this is are the spaces. For example if you have:

my_array=(option1 'option2 with space' option3)

The sed based solutions will transform it in -option1 -option2 -with -space -option3 (length 5), but the above bash expansion will transform it into -option1 -option2 with space -option3 (length still 3). Rarely, but sometimes this is important, for example:

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

I would prefer a plain bash way:

command "${my_array[@]/#/-}" "$1"

One reason for this are the spaces. For example if you have:

my_array=(option1 'option2 with space' option3)

The sed based solutions will transform it in -option1 -option2 -with -space -option3 (length 5), but the above bash expansion will transform it into -option1 -option2 with space -option3 (length still 3). Rarely, but sometimes this is important, for example:

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
Source Link
manatwork
  • 32.1k
  • 8
  • 104
  • 93

I would prefer a plain bash way:

command "${my_array[@]/#/-}" "$1"

One reason for this is are the spaces. For example if you have:

my_array=(option1 'option2 with space' option3)

The sed based solutions will transform it in -option1 -option2 -with -space -option3 (length 5), but the above bash expansion will transform it into -option1 -option2 with space -option3 (length still 3). Rarely, but sometimes this is important, for example:

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