bc

Does syntax of bash variables change when being passed to bc?


I noticed a solution on Codewars which had the following syntax:

#!/bin/bash
seven () {
    bc <<< "
    scale=0
    counter=0
    m=$1
    while( m > 99 ) {
        counter = counter + 1
        x = m / 10
        y = m % 10
        m = x - 2 * y
    }
    print m, \", \", counter
    "
}
seven "$1"

My question is regarding the variables used(m,x,counter). How is it that bash allows to use variables without using $variable_name?

Are there special cases (such as wraping code with double-quotes) that allow for this?


Solution

  • These are not bash variables but bc variables.

    The <<< operator introduces a "Here String" (see man bash), the following word undergoes expansions except for pathname expansion and word splitting and is sent to the standard input of the command, bc in this case.

    You can include a program for any other interpreter this way, i.e.

    python3 <<< 'x="Hello world!"
    print(x)'
    

    or

    dc <<< '
    100 3 /
    p'
    

    Also note that bash uses $x or ${x}, not $(x) (that would run the command x and return its output). $(x) for the variable x is used in Makefiles, though.