Search code examples
postgresqlshellubuntuterminalcron

Switch user before running cmd ubuntu


I'm trying to run a cron job in ubuntu server to backup my database every day.

so Im using this cmd:

sudo -i -u postgres && pg_dump -Fc DbName > DbName_backup.dump && ... && ... && ...

the problem I have is that you can not switch user and run command in a single statement, it never works.

I have to call sudo -i -u postgres then in another statement call pg_dump -Fc DbName > DbName_backup.dump && ... && ... && ...

But I want it to work in a single statement. in a single line!!!


Solution

  • sudo doesn't "switch users"; it runs a single command as another user. You can have that single command be a separate shell instance that parses and executes the rest of your list.

    sudo -i -u postgres sh -c 'pgdump -Fc DbName > DbName_backup.dump && ... && ... && ...'
    

    This adds a level of quoting, which might make providing the argument for sh -c more difficult. As such you might consider just putting your commands in a file to execute as single script.