views:

77

answers:

4

In a bash script, I have to include the same file several times in a row as an argument. Like this:

convert image.png image.png image.png [...] many_images.png

where image.png should be repeated a few times.

Is there a bash shorthand for repeating a pattern?

+2  A: 
#!/bin/bash

function repeat {
    for ((i=0;i<$2;++i)); do echo -n $1 " "; done
}

convert $(repeat image.png 3) many_images.png
Vlad Lazarenko
+7  A: 

You can do this using brace expansion:

convert image.png{,,} many_images.png

will produce:

convert image.png image.png image.png many_images.png

Brace expansion will repeat the string(s) before (and after) the braces for each comma-separated string within the braces producing a string consiting of the prefix, the comma-separated string and the suffix; and separating the generated strings by a space.

In this case the comma-separated string between the braces and the suffix are empty strings which will produce the string image.png three times.

Bart Sas
This is the best solution for a fixed, small number of repetitions, but doesn't work well for a large or flexible number of repetitions.
Philipp
This is neat. I like this. But as Philipp mentioned, I kind of have to prefer a parametrized solution.
BastiBechtold
+3  A: 

Here is a solution that uses arrays and is thus robust for strings containing spaces, newlines etc.

declare -a images
declare -i count=5
for ((i=0; i<count; ++i))
do
    images+=(image.png)
done
convert "${images[@]}" many_images.png
Philipp
You can get by without the `declare` statements. In your example, Bash will do the right thing for you. You would just set your count like this: `count=5`. The array will be created by virtue of the parentheses.
Dennis Williamson
+3  A: 

This works with a given integer (10 in the example below).

$ echo $(yes image.png | head -n10)
image.png image.png image.png image.png image.png image.png image.png image.png image.png image.png

It can also be used with xargs:

$ yes image.png | head -n10 | xargs echo
image.png image.png image.png image.png image.png image.png image.png image.png image.png image.png
strager
Yep - that's it...
smichak