2

I am new to bash scripting but after trying several syntax approaches and researching, I am a bit stuck storing the result of an external script call in my bash script. $r has no visible value when I echo it...

From the command line, it works as expected:

 ./external-prog 23334
 echo $?
 2
#!/bin/bash

# build the command
c="./external-prog 23334"

# invoke command that returns an integer value
eval "$c"

#collect result in $r
r=$(eval "$?")

#see result
echo $r
Slinky
  • 5,662
  • 14
  • 76
  • 130
  • 1
    Does this answer your question? [How do I set a variable to the output of a command in Bash?](https://stackoverflow.com/questions/4651437/how-do-i-set-a-variable-to-the-output-of-a-command-in-bash) – dibery Jan 23 '20 at 13:54

3 Answers3

1

It seems you just want to run the command and retrieve it's returned value, so there is no need far eval:

#!/bin/bash

# run the command
./external-prog 23334

#collect result in $r
r=$?

#see result
echo $r
Mickael B.
  • 4,755
  • 4
  • 24
  • 48
0

You can do it as below, storing the external script result in a variable :

c=$(./external-prog 23334)   
echo $c
nullPointer
  • 4,419
  • 1
  • 15
  • 27
0

This sequence $?will return the error code of the last process not the output. Check this out

$ echo ok; echo $?
ok
0

First echo printed 'ok' and the second one printed 0, which means command succeeded. And a non 0 code means some kind of error occured.

So this

 ./external-prog 23334
 echo $?
 2

Means that external-prog failed and the error code is 2 whatever it means. And to catch the output of some command to a var you need this

var=$(echo ok)
$ echo $var
ok
Ivan
  • 6,188
  • 1
  • 16
  • 23