Korn Shell Loop Problems

Very new to the Korn Shell, but I've been looking up loops online and it seems this should work. I'm just trying to convert an ip range in variables $A and $B and iterate the individual ip's out to new lines. Unfortunately I get {152..155} instead of 152, 153, 154, and 155.

# for i in {$A..$B}; do echo $C.$i; done 
219.19.188.{152..155}

Any tips for a BSD noobie?
I'm using OpenBSD if that helps.

You cannot perform a variable expansion inside a sequence expression.

Another approach would be using seq

for i in $( seq ${A} ${B} ); do echo $C.$i; done 
1 Like

I actually tried that too but it appears seq is not installed on my system:

# for i in $(seq $A $B); do echo $C.$i; done 
ksh: seq: not found

I tried adding it with pkg_add:

# pkg_add -r seq
Can't find seq

Do you know if the package for this is called something different?

---------- Post updated 01-06-14 at 12:11 AM ---------- Previous update was 01-05-14 at 11:37 PM ----------

I thought coreutils was the package that contained seq, but I'm still finding this is not installed. pkg_add can't find sysutils either...

Use a while loop instead:

while [ $A -le $B ]
do
        print $C.$A
        (( A++ ))
done
1 Like

I don't doubt this works on your system, but I'm getting some strange output for that?

# echo $A 
152
# echo $B
155
# while [ $A -le $B ]; do echo $C.$i; ((A++)); done 
219.19.188.10
219.19.188.10
219.19.188.10
219.19.188.10

---------- Post updated at 12:36 AM ---------- Previous update was at 12:27 AM ----------

Got it! I didn't see to change $C.$i to $C.$A. Thanks again Yoda!!!

ksh in OpenBSD is pdksh, which is mostly ksh88, which does not support the brace expansion syntax you were attempting to use.

BSD systems typically have jot instead of seq.

Regards,
Alister

1 Like

To add to what alister mentioned, you could probably install a valid ksh93 version on your system(s).

--

Yes you can in ksh , the parsing order for brace expansion is different than in bash .

If you use arithmetic evaluation with (( .. )), then why not use a for loop:

for (( i=$A; i<=$B; i++ )); do echo "$C.$i"; done

Or to keep it POSIXy:

i=$A
while [ $i -le $B ]; do
  printf "%s\n" "$C.$i"
  i=$((i+1))
done
1 Like

Scrutinizer last example is posix compatible - works fine in bash, ksh, dash, ...

If you like to use full ksh93 properties, then download it.
Or build from sources.

Can you please explain this statement? I thought brace expansion happens before variable expansion, so there is no way to use a variable in it :confused:

--EDIT--
Never mind, I see only bash performs brace expansion first.