bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [PATCH] examples/s-f/Bash_aliases: Fix off-by-one error


From: Phi Debian
Subject: Re: [PATCH] examples/s-f/Bash_aliases: Fix off-by-one error
Date: Sun, 21 Sep 2025 11:16:54 +0200

May be the 'repeat' function in the 'examples' is a bit lengthy, and use
subshells, the example I got is
===================================

# "repeat" command.  Like:
#
# repeat 10 echo foo
repeat ()
{
    local count="$1" i;
    shift;
    for i in $(seq 1 "$count");
    do
        eval "$@";
    done
}

# Subfunction needed by `repeat'.
seq ()
{
    local lower upper output;
    lower=$1 upper=$2;

    if [ $lower -ge $upper ]; then return; fi
    while [ $lower -le $upper ];
    do
echo -n "$lower "
        lower=$(($lower + 1))
    done
    echo "$lower"
}
===================================
May be a 1 liner version with no subshells could be something along those
lines.

$ repeat() { typeset n c;printf -v n '%*s' $1 ' ';shift;c="$@"; eval ${n//
/$c;};}

$ repeat 5 echo foo
foo
foo
foo
foo
foo

I don't know if printf -v n ... is equivalent to n=$(printf ...) I guess
there is a subshell here so that's why I used -v, if they are equiv then
the 1 liner can be shortened for a better readability :-)


reply via email to

[Prev in Thread] Current Thread [Next in Thread]