Is there a way to print same character repeatedly in bash, just like you can use this construct to do this in python:
print('%' * 3)
gives
%%%
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
&>word (and >&word redirects both stdout and stderr to the result of the expansion of word. In the cases above that is the file 1 . 2>&1 redirects stderr (fd 2) to the current value of stdout (fd 1).
There's actually a one-liner that can do this:
printf "%0.s-" {1..10}
prints
----------
Here's the breakdown of the arguments passed to printf
:
printf
to truncate the string if it's longer than the specified length, which is zeroprintf
, it could be anything (for a "%" you must escape it with another "%" first, i.e. "%%")printf
if you give it more arguments than there are specified in the format string is to loop back to the beginning of the format string and run it again.The end result of what's going on here then is that you're telling printf
that you want it to print a zero-length string with no extra characters if the string provided is longer than zero. Then after this zero-length string print a "-" (or any other set of characters). Then you provide it 10 arguments, so it prints 10 zero-length strings following each with a "-".
It's a one-liner that prints any number of repeating characters!
Edit:
Coincidentally, if you want to print $variable
characters you just have to change the argument slightly to use seq
rather than brace expansion as follows:
printf '%0.s-' $(seq 1 $variable)
This will instead pass arguments "1 2 3 4 ... $variable" to printf
, printing precisely $variable
instances of "-"
sure, just use printf
and a bit of bash string manipulation
$ s=$(printf "%-30s" "*") $ echo "${s// /*}" ******************************
There should be a shorter way, but currently that's how i would do it. You can make this into a function which you can store in a library for future use
printf_new() { str=$1 num=$2 v=$(printf "%-${num}s" "$str") echo "${v// /*}" }
Test run:
$ printf_new "*" 20 ******************** $ printf_new "*" 10 ********** $ printf_new "%" 10 %%%%%%%%%%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With