HOW TO : pipe results between commands when using sudo

Let’s say you are running a command as sudo and need to pass the output to a different command using pipe, you would run

sudo command1 | command 2

this usually results in the following error

-bash: /command2: Permission denied

The trick to fix is to run sudo with -c and enclose the commands in ” like below

sudo -c 'command1 | command 2'

essentially you are opening a shell with sudo and running the commands