Search code examples
stringbashconcatenation

Multiplying strings in bash script


I know that if I do print ("f" + 2 * "o") in python the output will be foo.

But how do I do the same thing in a bash script?


Solution

  • 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 times
    mmmmmmmmmm
    
    $ myString=$(printf "%10s");echo ${myString// /rep}         # echoes 'rep' 10 times
    reprepreprepreprepreprepreprep
    

    Wrapping it up in a more usable shell-function

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