Permission denied error while creating file by using script file

5,917

Solution 1

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

Solution 2

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.

Solution 3

Try this command,

sudo sh -c "echo 'blacklist snd_hda_intel' >  /etc/modprobe.d/sound.blacklist.conf"
Share:
5,917

Related videos on Youtube

r15
Author by

r15

Updated on September 18, 2022

Comments

  • r15
    r15 over 1 year

    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.