Search code examples
stringvariablesmathshcsh

Do math on CSH or SH only with string variables


I have string variables MIN and SEC (minute and seconds).

MIN = "1"
SEC = "34"

I want to do calculations on these.

TOTSEC = MIN*60 + SEC

I tried:

expr $SEC + $MIN * 60

Result:

expr: non-numeric argument

Let it be known I am running busybox on a custom microcomputer and so have no access to bash,bc, and that other solution provides.


Solution

  • In sh, by which I'll assume you mean a POSIX shell, your best option is to use Arithmetic Expansion:

    $ MIN=1
    $ SEC=34
    $ TOTSEC=$(( MIN * 60 + SEC ))
    $ printf '%d\n' "$TOTSEC"
    94
    

    In csh however, the built-in math works quite differently:

    % set MIN = 1
    % set SEC = 34
    % @ TOTSEC = ( $MIN * 60 + $SEC )
    % printf '%d\n' "$TOTSEC"
    94
    

    According to the man page, the @ command permits numeric calculations to be performed and the result assigned to a variable.

    Note that the expr command is external to the shell, so it should be usable from either one.

    In sh:

    $ TOTSEC=$(expr "$MIN" \* 60 + "$SEC")
    

    And in csh:

    % set TOTSEC = `expr "$MIN" \* 60 + "$SEC"`
    

    Note: your sh may not be POSIX compliant. Most likely, it's , which is the ancestor of dash and FreeBSD's /bin/sh. You'll need to test in your environment.