Ubuntu: Permission denied error while creating file by using script file


I have created a script file called black_list.sh.

#!/bin/bash    default_card=`head -1 /proc/asound/modules`  echo $default_card    if [ ! -e /etc/modprobe.d/sound.blacklist.conf ] && [[ "$default_card" =~ "snd_hda_intel" ]]; then          echo "blacklist snd_hda_intel" > /etc/modprobe.d/sound.blacklist.conf ---> not working              else          echo "Default sound card(snd_hda_intel) is already added in black list";  fi  

from this script file I am creating sound.blacklist.conf file in /etc/modprobe.d but I got /etc/modprobe.d/sound.blacklist.conf: Permission denied error.

So tried

echo itsme | sudo -S echo "blacklist snd_hda_intel" > /etc/modprobe.d/sound.blacklist.conf

but it also not worked so how can create a file in /etc/modprobe.d directory from my script file.


I'd personally use tee which you can run as root to append to files:

echo "blacklist snd_hda_intel" | sudo tee -a /etc/modprobe.d/sound.blacklist.conf  

But that might not be expected half-way through a script. If you're doing things that require root privileges, it might â€"and I'm not saying this for certainâ€" make more sense to only let root run the script by sticking this near the top of the script:

if [[ $EUID -ne 0 ]]; then    echo "Only root can run this. Run again with sudo" 2>&1    exit 1  fi  


Try this command,

sudo sh -c "echo 'blacklist snd_hda_intel' >  /etc/modprobe.d/sound.blacklist.conf"  


You have to enclose the output redirection into the sudo too.

The easiest way, for me, to do this is not to put the sudo inside your script, but to run your script using sudo.

To understand your problem, if you have the following command : $ sudo " " > /etc/file

The sudo action is only to execute <command> <params>, the redirection of output (>) happens out of the sudo in this case.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »