tags:

views:

84

answers:

4

I'm used to used the following feature of bash :

for i in ${1..23} ; do echo $i ; done

This doesn't generalize. For instance, replacing 23 by even $p does not work. As the documentation says, this is a purely syntactic feature.

What would you replace this with ?

Note : Of course, this could be done using a while and an auxiliary variable, but this is not what i'm looking for, even if it works. I'm failing back to this actually.

+2  A: 

If you have it available, the seq command can do similar. Your example might then be:

p=23
for i in `seq 1 $p`
do
    echo $i
done
martin clayton
+1  A: 

On linux, there is a seq command (unfortunately it's missing in OS X).

#!/bin/bash
p=23
for i in `seq 1 $p`;
do
    echo $i
done

OS X workaround: http://scruss.com/blog/2008/02/08/seq-for-os-x/comment-page-1/

The MYYN
OS X has the similar `jot`.
Dennis Williamson
thanks, learned a new command ;)
The MYYN
+2  A: 

You could use the seq tool to achieve the effect, I don't know if that's okay for your use case

~$ P=3 && for i in `seq 1 $P`; do echo $i; done
1
2
3

or litb's suggestion

~$ P=3 && for ((i=1;i<=$P;i++)); do echo $i; done
1
2
3
Vinko Vrsalovic
I was looking for a bash centric feature, that's why litb is better for my "use case". seq is rather neat too.
Gzorg
A: 
$ p=18
$ a='{1..$p}'
$ for num in $( eval echo $(eval echo $a) ); do echo $num; done