🐧 How to use Sudo when used with Output Redirection or Pipe

In this tutorial, I’ll show you how to use the sudo command when used with a redirect or pipe (| sign).

When using sudo with output redirection (>) or pipe (|), bash displays a Permission denied error message.

Next, I will show you different ways to solve this problem.

Use sudo with tree

For example, to redirect the output of the echo 1 command to the ip_forward file, run:

$ sudo echo 1 > /proc/sys/net/ipv4/ip_forward
bash: /proc/sys/net/ipv4/ip_forward: Permission denied

The above sudo command resulted in an error permission deniedbecause the redirection is done by a shell that doesn’t have write permission.

We can use the sudo command with the tee command to fix this error:

$ echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward

Using the above approach, the command executed before the pipe will not be executed as root (echo 1).

This is useful if you just want the output of a program that does not require root privileges.

If the command before the pipe requires root, we could use sudo before each command, for example:

$ sudo echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward > /dev/null

A similar approach that we can use to write “1” to the “ip_forward” file as in the previous examples is to level up the write process to the file.

Here’s an example:

$ sudo tee /proc/sys/net/ipv4/ip_forward > /dev/null << EOF
1
EOF

Start the shell with sudo -c

Another popular approach is to start another shell as root with the -c option.

Example:

$ sudo sh -c 'echo 1 > /proc/sys/net/ipv4/ip_forward'

Start the shell with sudo -s

Another way is to start a shell with sudo -s and then execute the command:

$ sudo -s
# echo 1 > /proc/sys/net/ipv4/ip_forward
# ^D
$

With a Bash script

Another way to run sudo with a redirect or pipe is to create a bash script with all your commands and run that script with sudo.

Let’s see how we can implement this.

First, we need to create a new file using any text editor like nano, vim, gedit, or whatever.

Let’s call it myscript.sh.

Then paste the following commands into myscript.sh and save the file:

#!/bin/sh
echo 1 > /proc/sys/net/ipv4/ip_forward

Now you just need to run the myscript.sh file using the sudo command:

$ sudo myscript.sh

Conclusion

We’ve looked at several ways to use sudo with output redirection or pipe and avoid permission denied errors.

If you know of another way to do this, or have any questions, post them in the comments section below.

Sponsored by this article – web design studio

Sidebar