head, tail and wc
If your busybox has head
, tail
and wc
built in, you might try the following:
head -c $n2 /dev/zero | tail -c +$n1 | wc -c
The first will generate a sequence of n2
zero bytes. The second will start at position n1
, counting from 1, so it will skip n1 - 1
bytes. Therefore the resulting sequence has n2 - n1 + 1
bytes. This count can be computed using wc -c
.
head, tail and ls or stat
Tried this with my busybox, although its configuration might differ from yours. I'm not sure whether wc
will be that more likely than expr
. If you have head
and tail
but no wc
, then you could probably write the result to a temporary file, and then use stat
or ls
to obtain the size as a string. Examples for this are included below.
seq and wc
If you have wc
but not head
and tail
, then you could substitute seq
instead:
seq $n1 $n2 | wc -l
seq, tr and stat
As your comment indicates you have no wc
but do have seq
, here is an alternative provided you have sufficuently complete ls
and also tr
, perhaps even stat
. Alas, I just noticed that tr
isn't in your list of applets either. Nevertheless, for future reference, here it is:
seq $n1 $n2 | tr -d [0-9] > tempfilename
stat -c%s tempfilename
This creates a sequence of n2 - n1 + 1
lines, then removes all digits, leaving only that many newlines, which it writes to a file. We then print its size.
dd and ls
But as you don't have tr
, you'll need something different. dd
might suite your needs, since you can use it a bit like head
or tail
.
dd if=/dev/zero of=tmp1 bs=1 count=$n2 # n2
dd if=tmp1 of=tmp2 bs=1 skip=$n1 # - n1
echo >> tmp2 # + 1
set -- dummy `ls -l tmp2`
echo $6
rm tmp1 tmp2
This creates a sequence of n2
null bytes, then skips the first n1
of it. It appends a single newline to add 1 to its size. Then it uses ls
to print the size of that file, and sets the positional variables $1
, $2
, … based on its output. $6
should be the column containing the size. Unless I missed something, this should all be available to you.
Alternative to busybox
If everything else fails, you might still implement your own digit-wise subtraction algorithm, using a lot of case distinctions. But that would require a lot of work, so you might be better of shipping a statically linked expr
binary, or something specifically designed for your use case, instead of a scripted approach.
ash
is so stripped down, I guess yourbusybox
doesn't have theawk
applet either? Or an externalbc
? – Sigurdfind / -name awk
orfind / -name bc
– Ideographyexpr
maybe? You might also want to check$ busybox awk
and$ busybox expr
in case there are just no symlinks. – Sigurdexpr
too, no good ... – Ideographybusybox --list
will at least give the list of available applets. – Adustuniq
have-u
? Then I have a new solution for you in the waiting. – Sigurd-u
option works! – Ideography