-   Linux - Newbie (
-   -   How to assign a variable to the output value of a program (

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?


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

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

Dark_Helmet 02-06-2011 11:43 PM

Your first attempt should work:

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

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:


#include <iostream>

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

  return 0;

Plus the compilation and command substitution tests:

$ 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 <>

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 01:10 AM.