Reputation: 154
If I try following:
varReturn=$(ls)
echo $varReturn
it shows me the correct output of the listed elements in the directory.
But if I try this one:
varReturn=$(/opt/vc/bin/tvservice -n)
echo $varReturn
it doesn't show me the expected output :/
My goal is to check if an HDMI Port is connected or not. It' very curious for me, why it works only for some commands.
I'm looking forward to getting some help here. I didn't figure out, what the problem is.
EDIT:
Now I've found another way and tried following:
varReturn=`tvservice -s`
echo $varReturn
this shows me the correct output:
But if I use another command, like this one:
varReturn=`tvservice -n`
echo $varReturn
It shows me no output at echo, but the output from the var (confusing).
It still shows me the output if I use following code:
varReturn=`tvservice -n`
#echo $varReturn
The output is shown without the blank space.
Upvotes: 1
Views: 102
Reputation: 5591
When you execute a shell command like varReturn=$(/opt/vc/bin/tvservice -n)
it will store the output to the variable only when the command executed successfully, else it will not hold any information because error/unsuccessful message will be redirected to standard error. Hence you have to redirected it to standard output like below:-
varReturn=$(/opt/vc/bin/tvservice -n 2>&1)
Now in both successful and unsuccessful execution case output will store in variable varReturn
.
Upvotes: 1
Reputation: 74615
There is at least one problem with this code:
varReturn=$(/opt/vc/bin/tvservice -n)
echo $varReturn
# ^ missing double quotes around this variable
Adding those quotes will ensure that the variable is passed as a single argument to echo
. Otherwise, echo
sees a list of arguments and outputs each one, separated by a space.
The next possible issue is that the command is outputting to standard error, rather than standard output, so it won't be captured by $()
or the old-fashioned equivalent ` `
. To correct this, try:
output=$(/opt/vc/bin/tvservice -n 2>&1)
# ^ redirect standard error to standard output
echo "$output"
Upvotes: 1