How to pass results of bc to a variable

98

Solution 1

If you're using bash, you'd better use an here string instead of a pipe as in:

bc <<< "scale=2;$var1/$var2"

This will save you a subshell.

Then, to store the output of a command, use a command substitution:

answer=$(bc <<< "scale=2;$var1/$var2")

Edit.

If you want something even cooler than bc, here's dc (reverse polish calculator):

answer=$(dc <<< "2k $var1 $var2/p")

Solution 2

Command substitution stores the output of a command into a variable.

var3=$(echo "scale=2;$var1/$var2" | bc)
Share:
98

Related videos on Youtube

shaolin
Author by

shaolin

Updated on September 18, 2022

Comments

  • shaolin
    shaolin almost 2 years

    I am writing a code for singly linked list and I am facing problem in writing its insert function. It is not inserting the new nodes and not printing them. I am not able to find the problem. Any help will be appreciated.

    Code:

    #include <iostream>
    
    using namespace std;
    
    
    class Node{
        int data;
        Node * next;
    
    public:
        Node(int data_)
        {
            data = data_;
            next = nullptr;
    
        }
    
        void insert(int no)
        {
            Node * index = this->next;
            while (index != nullptr)
            {
                index = index->next;
            }
            index = new Node(no);
        }
    
        void print()
        {
            Node * index = this;
            while (index != nullptr)
            {
                cout << index->data << ", ";
                index = index->next;
            }
        }
    
    };
    
    int main()
    {
        Node * head = new Node(1);
        head->insert(2);
        head->insert(3);
        head->insert(4);
        head->insert(5);
    
        head->print();
    
        system("pause");
        return 0;
    }
    

    Thanks

    • Deduplicator
      Deduplicator about 10 years
      Why are you putting your list head on the stack? Or shall that be the initialisation of the first link instead, in which case a more uniform interface would be a good idea?
    • crashmstr
      crashmstr about 10 years
      You need to assign something to next instead of the temporary index. Also, one would generally separate the Node from the List.
  • shaolin
    shaolin over 11 years
    Yes I'm using bash, can you please clarify on the subshell? Is there a disadvantage?
  • shaolin
    shaolin over 11 years
    Thank you! This got me exactly where I wanted to be, after probably an hour of researching. Thanks
  • gniourf_gniourf
    gniourf_gniourf over 11 years
    Each time you use a pipe | the command on the right of the pipe is executed in a subshell, and it takes resources to open a new subshell (it's like opening a new instance of bash to execute that command). If you can avoid it, avoid it. Here, piping an echo to bc will run the command bc in a subshell and is, in some sense, retarded (no offence), since bash has the wonderful here-string construct <<< to avoid stupid things like these.
  • h3.
    h3. over 11 years
    @gniourf_gniourf Then again, if you cared about resource usage, you'd use /bin/sh (dash) instead of bash, but dash doesn't have <<<.
  • shaolin
    shaolin over 11 years
    Thank you for the helpful information!! This is good information to know regarding preserving resources and subshells. I greatly appreciate you input.
  • gniourf_gniourf
    gniourf_gniourf over 11 years
    @Gilles please don't distort the discussion, you know I'm talking about useless and avoidable wastages of resource. Because going further in your direction, if I cared about resources I would not have a computer at all. Please let's be serious, so let me ask you a serious question: how can you (easily) check for the return code of bc if it's in a subshell like in your answer?
  • shaolin
    shaolin over 11 years
    @gniourf, thanks for your info!! really..it was helpful
  • h3.
    h3. over 11 years
    See a discussion with benchmarks on Unix & Linux: echo vs <<<, or Useless Use of echo in Bash Award? It seems that if you care about performance, you should use a heredoc, not a herestring, and most importantly you should use dash or ksh. Using <<< in bash is a waste of resources (but not an important one).
  • h3.
    h3. over 11 years
    By the way, you can get the output of bc with var3=$(echo … | bc). It's in $?, same as with var3=$(bc <<<…).
  • h3.
    h3. over 11 years
    Stephane Chazelas explains why <<< is slow: it creates a temporary file, which is slower than a pipe. The data has to come from somewhere after all.
  • gniourf_gniourf
    gniourf_gniourf over 11 years
    @Gilles just compare time for i in {1..10000}; do : <<< ""; done with time for i in {1..10000}; do echo "" | : ; done, you'll see a dramatic difference. Then you're right, a heredoc is slightly faster than a herestring. But it's more awkward to type as a one-liner.
  • h3.
    h3. over 11 years
    @gniourf_gniourf Now try it with the actual command here instead of an overly simplified example (which doesn't run an external command and doesn't read the data). With bash, and /tmp on tmpfs, I don't see any difference between echo … | and <<<. With ksh, <<< is indeed measurably faster (and faster than bash).
  • Admin
    Admin about 10 years
    Thanks it is working, can you please tell what was problem with my code. It looks similar to your but it don't works.
  • R Sahu
    R Sahu about 10 years
    @FarazAhmad I expanded my answer that tries explain the error in your code.
  • syntaxerror
    syntaxerror over 9 years
    @Gilles with <<<, it's not just about slowness! It's also always a problem on read-only environments, because on more complex scripts, your screen will be flooded with ugly error messages. And here's another thing people sometimes have difficulties to understand: this may happen __even under root! Because even root can't write everywhere, if partitions are mounted read-only. Very common on other companies' systems that you only have restricted access to. Likewise, recovery consoles would show that behavior by default as well.