#function repeat
repeat()
{
shift
let b="$@"
for i in {1..b} ; do echo Date starting `date` ; echo Before waiting `date`; sleep 6 ; echo Done waiting `date` ; "$@" ; done
}
The first time i tried to use this function it worked superbly, then in the past few days it worked 2 times then its working only once now
$ repeat 7 ls
the output used to show 7 times earlier, then it showed it only twice, now its showing the output only once.
Please let me know what mistake is there in the script which has never been changed from the first day.
You did not specify for what shell is the script intended. I will assume it's Bash.
Your function
repeat
is defined as (copied here from your post):You are calling it with
repeat 7 ls
. So$1
is7
and$2
isls
. The function executes:This throws away
$1
,$1
becomesls
,$2
is unset and$#
is 1.b
is set tols
.The loop will be executed once with
i
set to{1..b}
. (It looks like you wanted to try to generate some numbers using brace expansion; maybe{1..6}
which looks quite similar?)Display
Date starting date
,Before waiting date
, wait 6 seconds, and finally displayDone waiting date
. Maybe you wanted`date`
instead?$1
isls
and$#
is 1; this executesls
.End of the
for
loop.In general, the function will display a message, wait 6 seconds, display another message, then execute a command whose name is
$2
, possibly passing$3
, ... as arguments to the command.$1
is not used.(I won't comment on the affirmation that in the past this function used to do something else.)
A working function definition would be:
For example:
For production use some error checking may have to be added (there are at least two arguments, the first argument is a number, etc.).