function repeatString()
{
local -r string="${1}"
local -r numberToRepeat="${2}"
if [[ "${string}" != '' && "${numberToRepeat}" =~ ^[1-9][0-9]*$ ]]
then
local -r result="$(printf "%${numberToRepeat}s")"
echo -e "${result// /${string}}"
fi
}
Brace expansion can be used with integer literals:
for i in {1..100}; do echo -n =; done
A C-like loop allows the use of variables:
start=1
end=100
for ((i=$start; i<=$end; i++)); do echo -n =; done
Using the printf builtin:
printf '=%.0s' {1..100}
Specifying a precision here truncates the string to fit the specified width (0). As printf reuses the format string to consume all of the arguments, this simply prints "=" 100 times.
I guess the original purpose of the question was to do this just with the shell's built-in commands. So for loops and printfs would be legitimate, while rep, perl, and also jot below would not. Still, the following command
jot -s "/" -b "\\" $((COLUMNS/2))
for instance, prints a window-wide line of \/\/\/\/\/\/\/\/\/\/\/\/
Sample runs
Reference lib at: https://github.com/gdbtek/linux-cookbooks/blob/master/libraries/util.bash
In case that you want to repeat a character n times being n a VARIABLE number of times depending on, say, the length of a string you can do:
It displays:
There's more than one way to do it.
Using a loop:
Brace expansion can be used with integer literals:
A C-like loop allows the use of variables:
Using the
printf
builtin:Specifying a precision here truncates the string to fit the specified width (
0
). Asprintf
reuses the format string to consume all of the arguments, this simply prints"="
100 times.Using
head
(printf
, etc) andtr
:I guess the original purpose of the question was to do this just with the shell's built-in commands. So
for
loops andprintf
s would be legitimate, whilerep
,perl
, and alsojot
below would not. Still, the following commandjot -s "/" -b "\\" $((COLUMNS/2))
for instance, prints a window-wide line of
\/\/\/\/\/\/\/\/\/\/\/\/
Simplest is to use this one-liner in csh/tcsh: