Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat a few characters a few times in bash?

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?

like image 715
bastibe Avatar asked Nov 30 '22 18:11

bastibe


2 Answers

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.

like image 123
Bart Sas Avatar answered Dec 04 '22 05:12

Bart Sas


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
like image 36
strager Avatar answered Dec 04 '22 05:12

strager