In this tutorial, I will show how to use the sudo command when using with redirect or pipe. When using sudo with redirection (>) or pipe (|), bash output with Permission denied error message. Here I will show you different ways to fix that problem.
Use sudo with tee
For instance, to redirect the output of ‘echo 1’ command to ‘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 permission denied because redirection is done by the shell which doesn’t has write permission.
We can use sudo command with tee command to resolve this error:
$ echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward
Using the above approach, the executed command before the pipe will not run as root (echo 1). That’s useful if you just need the output of a program, which does not require root privileges.
In case the command before pipe requires root, we could use sudo before each command, as:
$ sudo echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward > /dev/null
The similar approach we can use to write “1” to “ip_forward” file, like in the previous examples, would be to elevate the process to write to the file.
An example would be as follows:
$ sudo tee /proc/sys/net/ipv4/ip_forward > /dev/null << EOF 1 EOF
Run shell with sudo -c
Another popular approach would be to run another shell as root using the
$ sudo sh -c 'echo 1 > /proc/sys/net/ipv4/ip_forward'
Run shell using sudo -s
Another way would be to launch a shell with
sudo -s and then run the command:
$ sudo -s # echo 1 > /proc/sys/net/ipv4/ip_forward # ^D $
By Using a Bash Script
There is yet another way to run sudo with redirect or pipe, and it is by creating a bash script with all your commands, and run that script with sudo.
Let see how we can accomplish that. First, we need to create a new file using any text editor, like nano, vim, gedit, or any other. Let’s name it “myscript.sh”.
Then paste the following commands to 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 with sudo command:
$ sudo myscript.sh
We have seen multiple ways to use sudo with redirect or pipe and avoid permission denied errors. If you know of another way to accomplish this or have any questions, please post them in the comment section below.