Multiplication on command line terminal

后端 未结 8 1888
有刺的猬
有刺的猬 2020-12-04 08:00

I\'m using a serial terminal to provide input into our lab experiment. I found that using

$ echo \"5X5\"

just returns a string of \"

相关标签:
8条回答
  • 2020-12-04 08:33

    A simple shell function (no sed needed) should do the trick of interpreting '5X5'

    $ function calc { bc -l <<< ${@//[xX]/*}; };
    $ calc 5X5
    25
    $ calc 5x5
    25
    $ calc '5*5'
    25
    
    0 讨论(0)
  • 2020-12-04 08:33

    I use this function which uses bc and thus supports floating point calculations:

    c () { 
        local a
        (( $# > 0 )) && a="$@" || read -r -p "calc: " a
        bc -l <<< "$a"
    }
    

    Example:

    $ c '5*5'
    25
    $ c 5/5
    1.00000000000000000000
    $ c 3.4/7.9
    .43037974683544303797
    

    Bash's arithmetic expansion doesn't support floats (but Korn shell and zsh do).

    Example:

    $ ksh -c 'echo "$((3.0 / 4))"'
    0.75
    
    0 讨论(0)
提交回复
热议问题