Multiplying strings in bash script Multiplying strings in bash script bash bash

Multiplying strings in bash script


You can use bash command substitution to be more portable across systems than to use a variant specific command.

$ myString=$(printf "%10s");echo ${myString// /m}           # echoes 'm' 10 timesmmmmmmmmmm$ myString=$(printf "%10s");echo ${myString// /rep}         # echoes 'rep' 10 timesreprepreprepreprepreprepreprep

Wrapping it up in a more usable shell-function

repeatChar() {    local input="$1"    local count="$2"    printf -v myString "%s" "%${count}s"    printf '%s\n' "${myString// /$input}"}$ repeatChar str 10strstrstrstrstrstrstrstrstrstr


You could simply use loop

$ for i in {1..4}; do echo -n 'm'; donemmmm


In bash you can use simple string indexing in a similar manner

#!/bin/bashoos="oooooooooooooo"n=2printf "%c%s\n" 'f' ${oos:0:n}

output

foo

Another approach simply concatenates characters into a string

#!/bin/bashn=2chr=ostr=for ((i = 0; i < n; i++)); do     str="$str$chr"doneprintf "f%s\n" "$str"

Output

foo

There are several more that can be used as well.