Permission denied when redirecting to sudo file

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2022-05-26

Context: I was working with audio, but the /etc/modprobe.d/alsa-loopback.conf file was only accessible with sudo.

But I wanted to add an entry to it, so I ran the following:

$ sudo echo "options snd-aloop enable=1,1,1,1,1 index=0,1,2,3,4" >> /etc/modprobe.d/alsa-loopback.conf

-bash: /etc/modprobe.d/alsa-loopback.conf: Permission denied

It failed, despite me using sudo in front of the command.

The issue is that redirection >> happens before the sudo command is invoked.

You will have to make sure that it's root that actually opens the file for writing in the redirection. Two ways:

Option 1: Use tee

Replace the redirect with | and tee -a (-a appends to the file instead of overwriting it)

echo "options snd-aloop enable=1,1,1,1,1 index=0,1,2,3,4" | sudo tee -a /etc/modprobe.d/alsa-loopback.conf

Option 2: Do redirection in a child process of a sudo process

# I wrap with: sudo sh -c ''
sudo sh -c 'echo "options snd-aloop enable=1,1,1,1,1 index=0,1,2,3,4" > /etc/modprobe.d/alsa-loopback.conf'