Search code examples
shellmathbusyboxdash-shell

Add/subtract variables in a really dumb shell


I am writing a shell script which works on my local /bin/sh fine (dash on Ubuntu 13.04), but I unltimately need to run it on a dumb box where I'm getting an error because of an operation on variables:

$((n2 - n1 + 1))

doesn't work, I get an error like:

syntax error: you disabled math support for $((arith)) syntax

I don't know a lot about the sh on there but I think this thing is busybox. How can I do maths on this dumb shell?


edit with list of applets

~ # busybox --list
[
arp
ash
cat
chgrp
chmod
chown
chroot
chvt
clear
cmp
cp
cut
date
dd
deallocvt
df
dmesg
du
echo
env
false
find
freeramdisk
ftpget
ftpput
grep
gunzip
gzip
hexdump
hwclock
ifconfig
ln
losetup
ls
md5sum
mkdir
mkfifo
mknod
mkswap
more
mount
mv
nslookup
ping
ping6
ps
pwd
renice
reset
rm
rmdir
route
seq
sh
sha1sum
sha256sum
sleep
sort
swapoff
swapon
switch_root
sync
tar
taskset
tee
telnet
test
tftp
time
top
touch
true
umount
uname
uniq
uptime
usleep
vconfig
vi
wget
whoami
yes

Solution

  • Another specific solution to your problem (n2 - n1 + 1) based on seq, sort -nr and uniq -u (POSIX-compliant).

    foo()
    {
        {
            seq 1 "$2"
            seq 0 "$1"
        } \
            | sort -n \
            | uniq -u \
            | grep -n "" \
            | sort -nr \
            | { read num; echo "${num%:*}"; }
    }
    
    $ foo 100 2000
    1901