Score:0

Why does sudo su not work in my script?

in flag

I want to change ownership, group membership and access rights in a script by a sequence of commands.

Some of them need root permissions.

I first did sudo su in a terminal and then ran all the necessary commands once in a row. I found out that after sudo su all macro definitions abc=<...> have to be put after sudo su, because it seems that root does not know about macros existing in the other context.

After all my commands worked as expected, I called histoy, removed the line numbers and framed the relevant part of it in sudo su ... exit.

I can paste this sequence of commands into a terminal and it runs fine.

However if I prepend it with a line #!/bin/bash and store it as a file and make that executable, that does not work:

I get prompted for the password, but then I end up at a command line level, with the prompt ending in #, which shows me that sudo su has worked. But the rest of my command sequence has not worked.

How can I achieve the other commands to be executed?

Being a command line newbie, I guess I haven't understood something important yet. Please explain how to do it and why.

Artur Meinild avatar
vn flag
Don't use `sudo` inside scripts. Instead, run the entire script as root. If it's a cronjob, run it from root's crontab.
in flag
Artur, do you suggest to put `sudo -u <username>` in front of all non-privileged commands and run the whole script as `sudo xyz.sz`? This however contradicts your first advice to never use sudo within a script.
Artur Meinild avatar
vn flag
I didn't say never, I said "don't". But the one example you give would be the exception, and that could be viable in some cases. ;-)
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.