Search code examples
shsu

How do I get pipe to work when passed in string for sh -c and su is involved


The pipe | to grep doesn't work -- it prints all the lines:

su - root -s /usr/bin/sh -c "java -version|grep build"

Solution

  • java -version writes to standard error, not standard output.

    su - root -s /usr/bin/sh -c "java -version 2>&1 |grep build"

    2>&1 copies standard error to standard output, so that it gets fed through the pipe and into grep.

    That said, grep doesn't have to be run as root, assuming the pipeline isn't being specified for use by something that just runs arbitrary code using su sh -c '...'.

    su - root -s /usr/bin/sh -c 'java -version' 2>&1 | grep build