1

No matter what I seem to do, I can't seem to get the output of a command to be assigned to a variable in bash. Although my script runs find without any errors, I'm not getting the result I want:

# Prompt if the user needs Qt
echo ""
echo "Checking for qt5-default."
echo ""

OUTPUT="$(sudo dpkg -s qt5-default)"

echo "OUTPUT:"
echo $OUTPUT

...

OUTPUT will never echo anything. However, if I do:

OUTPUT="$(ls -la)"

Then it works. I'm wondering why.


Here is what I mean:

Failure

As you can see, the "OUTPUT:" string comes after the command output, which means that the output wasn't stored in the variable, but was run in the main shell, which confuses me.

Here is what happens when OUTPUT="$(ls -la)":

Success

In this case, "OUTPUT:" comes before, showing that the echo command worked correctly.

Any ideas?

1
  • 4
    Sounds like it is using standard error instead of standard output. Try 2>&1 at the end of the command. Commented Feb 10, 2015 at 0:45

2 Answers 2

2
OUTPUT=$( dpkg -s qt5-default 2>&1 )

Should do what you're after. As Etan pointed out, dpkg's output goes to stderr, not stdout.

Sign up to request clarification or add additional context in comments.

Comments

1

dpkg -s do not require root privileges. As good practice never use sudo inside of scripts, but require a root privileges for a script.

About your question: why it happens? Because sudo runs in sub-shell (brackets $(...) opens a subshell)


I will try to find a good reference about bash pitfalls and subshell, I don't remember where I read about it. Try this: Subshell Pitfalls

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.