17

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?

learningbee
  • 333
  • 1
  • 5
  • 11
Jakob Kenda
  • 368
  • 1
  • 3
  • 12

5 Answers5

25

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
Inian
  • 80,270
  • 14
  • 142
  • 161
  • 7
    Use `printf -v myString '%*s' "$count"` instead of `myString=$(...)`. And use `local` to mark your variables local (or drop the local variables and use the parameters directly). – gniourf_gniourf Sep 14 '17 at 14:31
  • @gniourf_gniourf: Yup, it is a pretty old answer. Will make the change anyway! – Inian Sep 14 '17 at 14:35
  • You can simplify to `$ ${$(printf %10s)// /rep}` – James T. Oct 13 '21 at 19:04
  • @pjh: Fixed it, turned out to be a wrong edit – Inian Apr 25 '22 at 11:41
  • `repeatChar` works now. Its handling of counts with leading zeros may be surprising to some though. (`repeatChar str 09` fails with an `invalid octal number` error.) – pjh Apr 25 '22 at 12:19
6

You could simply use loop

$ for i in {1..4}; do echo -n 'm'; done
mmmm
ajay
  • 79
  • 4
5

That will do:

printf 'f'; printf 'o%.0s' {1..2}; echo

Look here for explanations on the "multiplying" part.

Community
  • 1
  • 1
Ohad Eytan
  • 8,114
  • 1
  • 22
  • 31
  • I like this answer most, but I would rewrite it as: `printf -- "f%s\n" $(printf -- "o%.0s" {1..2})` . The downside is that it needs a subshell, but it does the job quite well. – kvantour Apr 20 '22 at 20:01
2

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

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

output

foo

Another approach simply concatenates characters into a string

#!/bin/bash
n=2
chr=o
str=
for ((i = 0; i < n; i++)); do 
    str="$str$chr"
done
printf "f%s\n" "$str"

Output

foo

There are several more that can be used as well.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
0

You can create a function to loop a string for a specific count and use it in the loop you are executing with dynamic length. FYI a different version of oter answers.

  line_break()
    {
        for i in `seq 0 ${count}`
        do
          echo -n "########################"
        done
    }

    line_break 10

prints: ################

Mukundhan
  • 3,284
  • 23
  • 36