Physix
March 15, 2010, 6:54pm
1
Hi,
I have a problem with "for" and "while" loop in "sh".
I have:
#!/bin/sh
for i in $(seq 1 500000); do
echo $i
done
and it's working in sh on my ubuntu, but when I try to run this on unix(I have access to my university's unix) it crash:
syntax error at line 2: `$' unexpected
... second problem with while
#!/bin/sh
i=1;
while [ $i -le 1000000 ]; do
echo $i
i=$(($i+1));
done
It's working on ubuntu but not on unix
syntax error at line 5: `i=$' unexpected
Could anyone help me ?
Thank you for any suggestion
You are probably running a non-standard shell at school. Schools excel at picking oddball teaching environments.
On the school box show the output of:
grep yourusername /etc/passwd
OR it could be a bourne shell. Modern shells would reject those commands as you found out. You can try substituting
` ` (those are backticks ) for the $( ) construct.
Physix
March 16, 2010, 4:14am
3
grep yourusername /etc/passwd:
w29185:x:4496:203:MyName:/export/home/w29185:/bin/bash
I tried:
#!/bin/sh
for i in `seq 1 500000`; do
echo $i
done
... and
seq: not found
In the first question you need to write the following script
#!/bin/sh
for i in `seq 1 10`;
do
echo $i
done
In the second code is working correctly in my system.
seq is an external program which need to be installed on your system.
i=$(($i+1))
is a POSIX syntax, if your shell don't support it you can try:
i=`expr $i + 1`
or:
let i=i+1
Physix
March 16, 2010, 5:07am
6
i=`expr $i + 1`
ok thx is't working
And what aboute for in sh if my shell doesn't support seq and I need ex 1000 repetition
Something like this?
#!/bin/sh
i=1
while [ $i -le 1000 ]; do
echo $i
let i=i+1
done
Instead of let you can use this expr.
#!/bin/sh
i=1
while [ $i -le 1000 ];
do
echo $i
i=`expr $i + 1`
done