I've looked at How do I run a 'sudo' command inside a script? but this seems to be a different issue.
I want to run a script to change from root to the mastodon user using su
, run Rails commands, and then exit back to the root account and restart mastodon.
Manually, I can log into root via ssh root@123.456.78.90
which gives me the root@Mastodon:~#
shell. Then I use sudo su - mastodon
to change to the mastodon account (I am not prompted for a password) and then cd live
. Then I can run the Rails commands, etc., and they work, and then I can exit
and run systemctl restart mastodon-*
.
But my shell script to do the same thing doesn't work. The restartall
script is
#!/bin/bash
sudo su - mastodon
cd live
RAILS_ENV=production bundle exec rake tmp:cache:clear
RAILS_ENV=production bundle exec rails assets:generate_static_pages
RAILS_ENV=production bundle exec rails assets:precompile
exit
systemctl restart mastodon-*
and I run it this way
root@Mastodon:~# ./restartall
The terminal user and path change to mastodon@MyMastodon
, but that's all; the script fails wth:
./restartall: line 5: cd: live: No such file or directory
I also tried root@Mastodon:~# sudo ./restartall
What am I doing wrong in using su
to change to the mastodon
user?
Will simply using exit
correctly take the script back to root@Mastodon
before systemctl restart mastodon-*
?
sudo su -c 'cd live' mastodon
and got "permission denied." – BlueDogRanch Feb 25 '23 at 21:52su
andsu -
are not quite the same thing; you'd needsudo su -c 'cd live' - mastodon
or (perhaps clearer)sudo su -l -c 'cd live' mastodon
– steeldriver Feb 25 '23 at 21:59sudo su - mastodon -c "cd live (bundle commands here) exit"
works and it exits correctly and runssystemctl restart mastodon-*
, but throws "bundle: command not found" errors. – BlueDogRanch Feb 25 '23 at 22:08sudo su -l -c 'cd live RAILS_ENV=production bundle exec rake tmp:cache:clear RAILS_ENV=production bundle exec rails assets:generate_static_pages RAILS_ENV=production bundle exec rails assets:precompile exit' mastodon
– BlueDogRanch Feb 25 '23 at 22:18