Pipes - GradedJestRisk/linux-training GitHub Wiki

Pipes

piping

Pass some content to another command

echo "." | ls

as root

You can't pipe or redirect between subshells keeping root privileges

sudo echo 'some text' >> /path/to/privileged/file

You can run command interactively in root mode

sudo --login
echo 'some text' >> /path/to/privileged/file

Or consider sponge

echo "some text" | sudo sponge /path/to/privileged/file

sponge reads standard input and writes it out to the specified file. Unlike a shell redirect, sponge soaks up all its input before writing the output file. This allows constructing pipelines that read from and write to the same file.

SO

pass argument

Sometimes the command doesn't read form stdin, eg. git add

Use xargs to send stdin in argument (SO)

echo "hello" | xargs echo $1
hello

Run command only if the pipe send something

echo "hello" | xargs --no-run-if-empty echo $1
diff <(echo "a" ) <(echo "a") | wc -l
#0
diff <(echo "a" ) <(echo "a") | xargs --no-run-if-empty echo "I shall not be displayed"
diff <(echo "a" ) <(echo "b") | xargs --no-run-if-empty echo "I've been run, with arguments"