for i in {1..40}
do
echo $i
done
I got
{1..40}
and I would like to have something like
1
2
3
and so on
so I can use the variable i
inside a command's parameter.
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityIn bash 3.0+ (as well as zsh and ksh93), {1..40}
will expand to the numbers from 1-40 (inclusive). In a POSIX shell like dash (which is typical of /bin/sh
in e.g. Ubuntu), it will not work (we call this issue a "bashism").
On systems with the GNU utilities, you can use seq
to accomplish this:
for i in $(seq 1 40)
do
echo $i
done
To be more portable, you'll have to manually increment $i
in a while
loop:
i=1
while [ $i -le 40 ]
do
echo $i
i=$((i+1))
done
This portable version is also very slightly faster since it lacks the external command.
while
could be i=; until [ "$((i+=1))" -gt 40 ]; do echo "$i". done
and, if run in dash
is likely faster than anything you would run in bash
anyway.
$((i+=1))
syntax has been unreliable in my past experiences with older UNIX systems. I don't like until
, especially when while
will work fine: try i=0; while [ $((i+=1)) -le 40 ]; do echo $i; done
Mar 25, 2015 at 22:02
until
, while
stuff is just style, but what's unreliable about the increment += assign? Basically any of those assignments you can do in C you should be able to do in the shell. |=
^=
&=
/=
*=
-=
%=
. That is, you can do them in a POSIX shell. But you should quote the math expansion in the [
test ]
maybe if you don't get explicit about $IFS
before hand.
$(())
notation. Interesting note about quotation, but if $IFS
is tampered with, a lot will break; [
is the least of your worries ;-)
Mar 25, 2015 at 22:08
posh
though it won't like v=; : "$((v+=1))"
(though it should) but instead prefers v=0; : "$((v+=1))"
.
bash
. What shell are you using?sh yourscript
instead of./yourscript
(wheresh
may be another shell, such asdash
).