2

I am pretty sure this has been asked already in some form, I just cannot come up with a good find to search it.

I want to have a script that do things N times and to which I can pass as a variable what command to issue N times. In general the command might use the iterator value to change something. For instance I would like to do something like

~> doNtimes.sh 10 0 "ls *$(($2 + $i ))*.gnu | wc -l;"

where doNtime.sh is something like

  for ((i=0; i < $1; ++i)); do 
       echo "iterator=$i"; 
       $3
  done

of course the current use of double quotes make me fail. I have tried with single quotes but does not work either (although for a different reason). The fact that I have variable with spaces and contains variable to be evaluated in the script makes impossible for me to find the right syntax ... any idea?

2 Answers 2

1

You need eval:

for ((i=0; i < $1; ++i)); do 
    echo "iterator=$i"; 
    # for debugging
    echo eval "$3"
    eval "$3"
done

Of course, you must pay attention to the right quoting in the command string. Your example ls *$(($2 + $i ))*.gnu | wc -l is dangerous in this sense because the variable references are resolved within "" i.e. before the script runs. You need single quotes:

doNtimes.sh 10 0 'ls *$(($2 + $i ))*.gnu | wc -l'
2
  • 1
    Hi Hauke, for my case it seems that the trick was more on putting an escape on the dollar ... "ls \$((200 + \$i )).gnu | wc -l" works as the variables are not evaluated in CLI but are then in the loop. The loop, as a matter of fact does not require any special astuce with quoting. Escaping is the key, IMHO. Anyways, thanks for your input!
    – Rho Phi
    Jan 15, 2015 at 21:41
  • @RobertoFranceschini I was wrong about the quoting requirements but you need eval for the pipeline to work. Jan 15, 2015 at 22:06
0
yes _do | head -n 10 | 3<&0 0>&- \
<<\INIT sh -s -- my args
    alias _do='echo these are "$@."'
    exec <&3 3>&- 
#END
INIT

You can also force feed a shell pretty easily. xargs would work as well.

OUTPUT:

these are my args.
these are my args.
these are my args.
these are my args.
these are my args.
these are my args.
these are my args.
these are my args.
these are my args.
these are my args.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .