Home > Net >  How do I glob and repeat command line argument with option repeated?
How do I glob and repeat command line argument with option repeated?

Time:02-16

I want to run a command line program for multiple inputs like this

image_convert -I ./a.png -I ./b.png ...

The -I is mandatory before each file. Can I somehow do this for all png files in the directory using bash shell glob syntax, e.g., something like this

image_convert -I ./*.png

(this doesn't work)

CodePudding user response:

image_convert -I ./*.png would expand to something like: image_convert -I ./a.png ./b.png.

You can use a loop and an array instead:

args=()
for arg in ./*.png
do
  [ -f "$arg" ] || continue
  args =("-I" "$arg")
done
image_convert "${args[@]}"

If you want to deal with a POSIX shell, then you can utilize the array $@:

set -- # empty $@
for arg in ./*.png
do
  [ -f "$arg" ] || continue
  set -- "$@" -I "$arg" # Re-set $@ with '-I "$arg"' added for each iteration
done
image_convert "$@"

CodePudding user response:

You could combine printf with xargs:

printf -- '-I\0%s\0' *.png | xargs -0 image_convert
  • Related