LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to assign a variable to the output value of a program (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-assign-a-variable-to-the-output-value-of-a-program-861105/)

BeyondSora 02-06-2011 11:17 PM

How to assign a variable to the output value of a program
 
so i wrote myself a very simple hellworld program in c++

...the usual stuff
int main()
{
cout << "helloworld" << endl;
return 0;
}

------------------
how do i assign output value of this program to a variable in shell?

Code:

myvar=$(./a.out); echo $myvar
prints "0" as myvar got assigned to the return value
Code:

./a.out|myvar=$?; echo $myvar
doesnt work either

Dark_Helmet 02-06-2011 11:43 PM

Your first attempt should work:
Code:

myvar=$(./a.out); echo $myvar
When you run ./a.out on its own, do you get the expected "helloworld"?

EDIT:
Also, what shell are you running? bash? ksh? tcsh?

BeyondSora 02-07-2011 12:13 AM

yes I do get "helloworld"

I am using bash

---------------------
this is so confusing, i made myself the same program using python
and it works......
but just not for c++... this doesnt make sense to me D:

Dark_Helmet 02-07-2011 12:46 AM

Well, if it works with your python program, then I'd say you've eliminated bash as a suspect. So it's likely something funky with the c++. For comparison, here's a quickie hello world source, compile, and run:

helloworld.cpp
Code:

#include <iostream>

int main( int argc, char *argv[] )
{
  std::cout << "Hello world!" << std::endl;

  return 0;
}

Plus the compilation and command substitution tests:
Code:

$ g++ -o a.out helloworld.cpp
$ ./a.out
Hello world!
$ myvar=$(./a.out); echo "$myvar - test"
Hello world! - test
$ bash --version
GNU bash, version 4.1.5(1)-release (i486-pc-linux-gnu)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.



All times are GMT -5. The time now is 09:39 PM.