Multiline write fails (Permission denied)

bash, linux, ubuntu

Solution

The output redirection is processed before `sudo` runs, so you are still trying to open the file as yourself, not as root. One option is to use `tee` instead of `cat`, since `tee`, rather than the current shell, will open the file for writing.

sudo tee /etc/init/myservice.conf > /dev/null <<EOF
start on runlevel [2345]

stop on runlevel [06]

respawn

script

  cd ~/somefolder

  . venv/bin/activate

  exec python manage.py runserver 0.0.0.0:8080

end script
EOF

While the delimiter used doesn't really matter, it makes more sense to use something that indicates end of file, rather than end of line :) `tee` actually writes its input to both the named file(s) and standard output, but you don't need to see what you are writing, hence the redirection to `/dev/null`.

Problem

I would like to write a multiline string to a file that is only accessible with root permissions. This is what I have so far: ``` sudo cat > /etc/init/myservice.conf <<EOL start on runlevel [2345] stop on runlevel [06] respawn script cd ~/somefolder . venv/bin/activate exec python manage.py runserver 0.0.0.0:8080 end script EOL ``` When this command, all I get is "Permission Denied". Creating the file manually works.

Original source