1

I want to use shell scripts to set up my virtual machine. Example script.sh has

pip install wheel
pip install cookiecutter
pip install flask 
pip install gunicorn
pip install uwsgi

Then I want it to create a service file on location /etc/systemd/system/website.service that contains the following:

[Unit]
Description=Gunicorn instance to serve website
After=network.target

[Service]
User=$1
Group=www-data
WorkingDirectory=/home/$1/website
Environment="PATH=/home/$1/website/venv/bin"
ExecStart=/home/$1/website/venv/bin/gunicorn --workers 3 --bind unix:website.sock -m 007 wsgi:app

[Install]
WantedBy=multi-user.target

Where $1 gets replaced by the user($USER) executing the shell script. Nicest solution is if I would put this in a separate file and then copy the file to the specified location while replacing the argument. Important is that this reguires sudo on the pasting due to location.

Something like:

pip install wheel
pip install cookiecutter
pip install flask 
pip install gunicorn
pip install uwsgi
sudo echo file_containing_text.txt $USER > /etc/systemd/system/website.service

but for the love of me I can't get this to work.

M.R.
  • 13

2 Answers2

1

There's probably a better way to do this, but to achieve specifically what you're trying to do, you could use a "here document":

#!/bin/bash
pip install wheel
pip install cookiecutter
pip install flask 
pip install gunicorn
pip install uwsgi
sudo cat > /etc/systemd/system/website.service << EOF
[Unit]
Description=Gunicorn instance to serve website
After=network.target

[Service]
User=${USER}
Group=www-data
WorkingDirectory=/home/${USER}/website
Environment="PATH=/home/${USER}/website/venv/bin"
ExecStart=/home/${USER}/website/venv/bin/gunicorn --workers 3 --bind unix:website.sock -m 007 wsgi:app

[Install]
WantedBy=multi-user.target
EOF

Everything between << TOKEN and a line with only TOKEN is the document; in my example I used EOF as the token.

Andy Dalton
  • 13,993
  • Thanks! Its not the more advanced " separate file" solution but if it works it works :D – M.R. Nov 03 '19 at 15:41
0

Yes, the problem is that the shell (running as you) tries to process the redirection before launching the sudo-command.

tee works well here:

sed 's/\$1/'"$USER"'/' your_file | sudo tee /some/privileged/file

And if you don't want to see the output on the screen, add >/dev/null at the end.

Or, you could spawn a shell as sudo:

export USER
sudo sh -c 'sed "s/\\\$1/$USER/" your_file > /some/privileged/file'

but we're clearly in quoting hell here.

glenn jackman
  • 85,964