This is not a duplicate of the other question for two reasons. That question did not specify that the answer had to be POSIX. The marked answer for that question does not run correctly in a Dash shell. (I don't know how to tell if the answer is POSIX but it didn't run on the latest version of Dash.
To clarify, I would like to only use POSIX shell builtins. I should have made this clearer. As far as I know, seq is a GNU util, which means I would have to spawn an external program. I would like to not spawn any external programs.
I would like to know the most efficient way to multiply a string in a shell script. For example the script would perform as follows...
./multiplychar "*" "5"
*****
./multiplychar "*" "1"
*
./multiplychar "*" "0"
# It would not output anything
I cannot seem to find it anymore, but I found this question for bash a long time ago. All the answers, however, either used an external program like Perl e.x. perl -E "print '$' x $2"
or used bashisms.
I would like to know how to accomplish this natively in a POSIX shell. I am using dash. If there are multiple ways, in case it's relevant for efficiency sake, I am dealing with small numbers less than 100. (It's a script for a strictly text based volume bar notification.)
Shell: dash
OS: Arch Linux
Fully POSIX way of doing it would be using the following script. This script doesn't create any external process, only using the built-in functionality.
Calling this script
./multiplychar "*" 5
will print*****
.Here is how this script works,
The
_seq()
function runs in a subshell so that it doesn't affect any variables. Calling_seq 5
will output" 1 2 3 4 5 "
. Whitespaces don't matter on thefor
loop.In both the
_seq()
function and the main function, the output is stored in a variable named$buf
so that we callprintf
only once.This should be the most efficient and POSIX way to have this functionality on your shell.