Search code examples
bashvariablessyntaxbc

Passing bc into a variable isn't working right for me in Bash


I think I'm going crazy, I have a different script that's working fine with the usual way of passing the output of bc into a variable but this one I just can't get working.

The relevant bits of code are this:

PERCENT_MARKUP=".5"

$percentonumber=$(bc -l <<<"$PERCENT_MARKUP/100")
echo "Percent to number = $percentonumber"

$numbertomultiply=$(bc -l <<<"$percentonumber + 1")
echo "Number to multiply = $numbertomultiply"

$MARKUP=$(bc -l <<<"$buyVal * $numbertomultiply")
#$MARKUP=$(bc -l <<<"$buyVal * (1+($PERCENT_MARKUP/100))")
echo "Markup = $MARKUP"

Originally, I only had the second to last line that's currently commented out but I broke it down to try and troubleshoot.

The error I'm getting when I'm trying to run it is:

./sell_zombie_brains: line 65: =.00500000000000000000: command not found

where the .0050000000000000 is replaced by the output of bc. I've even tried the following at multiple points in the file including right after #!/bin/bash with and without -l

$test=`bc -l <<<"1"`
echo "$test"
echo
$test=$(bc -l <<<"1")
echo "$test"
echo
$test=$(echo "1"|bc -l)
echo "$test"
echo

And each one outputs ./sell_zombie_brains: line 68: =1: command not found

I'm really at my wits end. I don't know what I'm missing here. Any insight as to why it's behaving this way is appreciated.


Solution

  • You can't assign variables with the sigil $ :

    instead of

    $percentonumber=$()
    

    it's

    percentonumber=$()
    

    If you are a beginner, some good pointers to start learning :

    https://stackoverflow.com/tags/bash/info
    FAQ
    Guide
    Ref
    bash hackers
    quotes
    Check your script

    And avoid people recommendations saying to learn with tldp.org web site, the tldp bash guide -ABS in particular) is outdated, and in some cases just plain wrong. The BashGuide and the bash-hackers' wiki are far more reliable.