Technic1an
Technic1an

Reputation: 2797

How to store output from a bash command in a variable

Hello I am trying to store an OS X command in a variable and I am having problems doing so. Here is my code:

#! /bin/bash
Output=$(dscl . -read /Users/root AuthenticationAuthority)
Check="No such key: AuthenticationAuthority"  

if [ "$Output" = "$Check" ]
    then
       echo "OK"
      else
    echo "FALSE"
fi

I have done this before with commands such as "defaults read...." and it works fine but the dscl . -read will not store the output in the variable. Any ideas?

Upvotes: 0

Views: 3640

Answers (2)

0xFC
0xFC

Reputation: 171

On failure, the dscl command, as well as all standard shell commands, outputs the error message on stderr, whereas $(...) only captures stdout.

You have to merge the two streams first:

Output=$(dscl . -read /Users/root AuthenticationAuthority 2>&1)

Upvotes: 7

Brian Campbell
Brian Campbell

Reputation: 332736

When the dscl command succeeds, its output goes to stdout, which is captured by the command substitution.

When there is an error, the message is printed to stderr instead.

To capture either stdout or stderr, you can redirect stderr in the command to go to stdout:

Output=$(dscl . -read /Users/root AuthenticationAuthority 2>&1)

Upvotes: 0

Related Questions