0

I am trying to get the output of a command set to a variable but when I run it with the Command substitution, the command returns a blank line

[user@host bin]$ ./MyAppRead 4
Segmentation fault (core dumped)
[user@host bin]$ BALLS=$(./MyAppRead 4)
[user@host bin]$ echo $BALLS

[user@host bin]$

I am expecting BALLS to be set to "Segmentation fault (core dumped)" but it is blank?

-EDIT-

Changed to reflect the advice below. But still coming back blank

[user@host bin]$ ./MyAppRead 4
Segmentation fault (core dumped)
[user@host bin]$ BALLS=$(./MyAppRead 4 2>&1)
[user@host bin]$ echo $BALLS

[user@host bin]$

2 Answers 2

6

$() captures standard output, not standard error. A segmentation fault error will go to standard error.

If you want both, you can capture both this way:

BALLS=$(./MyAppRead 4 2>&1)
Sign up to request clarification or add additional context in comments.

1 Comment

Edited above to show the new command with your advice, but still the same blank output
4

Segmentation fault is a signal, and if you program gets it, it will be terminated and bash will print Segmentation fault message to shell (not program) stderr.

You can get this output by trapping segmentation fault signal with trap. Write this in file script.sh

/bin/bash
# script.sh
trap "Segmentation fault (core dumped)" 11
./MyAppRead 4 

and then execute this

chmod +x script.sh
BALLS=$(./script.sh 2>&1)
echo $BALLS

1 Comment

That makes sense. Thanks! I actually decided instead to trigger on a successful message rather than a segfault and that worked on stdout just fine. But good to know for future use

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.