Himangshu Paul
Himangshu Paul

Reputation: 123

Output of a fortran program into a variable

I have an interactive FORTRAN program that requires various inputs from the user. Now, I want to store the output of this Fortran program into a variable and use this value in a shell script. I tried

 var=`./test` and var=$(./test)

but in both the cases, it does not prompt the user for input and stays idle. What should I do? A piece of example fortran code is like this

  test.f  

  program test
  character*1 resp1, resp3
  integer resp2, ans

  write(*,*) 'Think of a prime number less than 10'
  write(*,*) 'Say whether it is odd or even'
  write(*,*) 'Write o/e'
  read(*,*) resp1
  if ( resp1 .EQ. 'e' ) then
   ans=2
  else
   write(*,*) 'Is the number close to 4 or 8'
   read (*,*) resp2
   if ( resp2 == 8 ) then
    ans=7
   else
    write(*,*) 'Is the number greater than or less than 4'
    write(*,*) 'Write g or l'
    read (*,*) resp3
    if ( resp3 .EQ. 'l' ) then
     ans=3
    else
     ans=5
    end if
   end if
  end if
  write(*,*) ans
  end

  Compiled as gfortran test.f -o test

Then I used a script like this

 test.sh

 var=`./test`
 echo "The answer you are looking for is " $var

I believe there is something very trivial that I am not able to find. Please help me.

P.S. This is just an example code and script and my actual script and code is far different.

Upvotes: 4

Views: 585

Answers (1)

Eric Duminil
Eric Duminil

Reputation: 54303

Jean-François Fabre is right.

program test 
character*1 resp1, resp3 
integer resp2, ans 

write(0,*) 'Think of a prime number less than 10' 
write(0,*) 'Say whether it is odd or even' 
write(0,*) 'Write o/e' 
read(5,*) resp1 
if ( resp1 .EQ. 'e' ) then 
 ans=2 
else 
 write(0,*) 'Is the number close to 4 or 8' 
 read (5,*) resp2 
 if ( resp2 == 8 ) then 
  ans=7 
 else 
  write(0,*) 'Is the number greater than or less than 4' 
  write(0,*) 'Write g or l' 
  read (5,*) resp3 
  if ( resp3 .EQ. 'l' ) then 
   ans=3 
  else 
   ans=5 
  end if 
 end if 
end if 
write(6,*) ans 
end 

Questions are stderr (0), Answers are stdin (5), Result is stdout (6)

var=`./test`

works fine after that.

Upvotes: 3

Related Questions