0

I want to save a command output to an variable in a bash script. I've tried possibilities that I've found here in this forum but it doesn't work for my script.

I use the command: cangen vcan0 -g 4 -I 7E -L 8 -D r -v to generate CAN data. -g, -I, -L, -D, -V are parameter to define how the CAN data have to be generate.

Normally i get the data printed on the Terminal like this:

cangen output on bash

I want to store this output in a variable:

#!/bin/bash

#We have to generate a virtual CAN bus Interface

sudo modprobe vcan
sudo ip link add dev vcan0 type vcan
sudo ip link set up vcan0

candata= `(cangen vcan0 -g 0.008 -I 7E -L 8 -D r -v)`
echo $candata

and when i run my script, i do not obtain the output from my cangen-command. I get the output:

RTNETLINK answers: File exists

I do not have much experience with Linux and bash script programming. Can someone help me?

Aserre
  • 4,916
  • 5
  • 33
  • 56
  • 1
    The error message seems to be unrelated to the construct you are asking about. Your variable already contains the output from the program `cangen` (though the parentheses are superfluous), but the error message might mean that the output is empty. – tripleee Aug 11 '16 at 11:09

1 Answers1

1

I think that your script works, this message is the content of $candata, and the reason for it that the vcan0 device already exists. (Have you tried several times already maybe?)

Anyhow I would suggest to write:

candata=$(cangen vcan0 -g 0.008 -I 7E -L 8 -D r -v)

or

candata=`cangen vcan0 -g 0.008 -I 7E -L 8 -D r -v`

As you have written it, you open a sub-shell which rises complexity for nothing.

  • Thanks for your answer. I´ve tried it several time and i got the same message. If my script would work, I should be able to see the data. I have tried your suggestions and I always get the same message – Morfeo Rejocktana Aug 11 '16 at 12:27
  • I concurr with what tripleee commented above. I still believe that the script (as bash is concerned) is correct and the problem is somewhere else. – Emilio Pastor Mira Aug 11 '16 at 13:37
  • The problem was the command: sudo ip link add dev vcan0 type vcan This command must be run only once. – Morfeo Rejocktana Aug 11 '16 at 14:58