Bash print stderr only, not stdout

LinuxBash

Linux Problem Overview


I want to lint a file, and print the stderr (error message), but do not print the stdout (saying the file is OK).

php -l "foo/bar.php"
  • If there are no errors, it prints a "No errors" message to stdout.
  • If there are errors, it prints a detailed message to stderr. I want only this one.

I figure it will be some magic with >&, but I never understood how those work.

What I want is to consume all stdout, keep stderr.

(Sorry if this is dulicate, but I haven't found any question exactly about this)

Linux Solutions


Solution 1 - Linux

Just send the stdout to null:

cmd > /dev/null

This retains stderr, but suppresses stdout.

Solution 2 - Linux

You can use:

php -l "foo/bar.php" 2>&1 > /dev/null

i.e. redirect stderr to stdout and stdout to /dev/null in order to get only stderr on your terminal.

Solution 3 - Linux

> If there are no errors, it prints a "No errors" message to stdout. > If there are errors, it prints a detailed message to stderr. I want only this one.

This would print the error message if one is sent or No error. if empty.

error=$(php -l "foo/bar.php" 2>&1 >/dev/null)
[[ -z $error ]] && error="No error."
echo "$error"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMightyPorkView Question on Stackoverflow
Solution 1 - LinuxnneonneoView Answer on Stackoverflow
Solution 2 - LinuxanubhavaView Answer on Stackoverflow
Solution 3 - LinuxkonsoleboxView Answer on Stackoverflow