如何以降低的权限运行脚本的一部分?

Chr*_*urm 7 linux bash permissions shell-script

我有以下问题:在每台运行 Postgresql 的机器上,都有一个特殊的用户postgres。此用户具有对数据库服务器的管理访问权限。

现在我想编写一个 Bash 脚本,它使用 psql 作为用户postgres执行数据库命令(psql 应作为用户postgres执行,而不是脚本)。到目前为止,这不是问题:我可以以用户postgres 的身份运行脚本。

但是,我想将 psql 的输出写入postgres没有写访问权限的目录中的文件。

我怎样才能做到这一点?

我想过在脚本本身中更改 EUID,但是:

  1. 我找不到在 Bash 脚本中更改 EUID 的方法
  2. 使用类似的东西时如何更改 EUID
    psql -U postgres -c "<command>" > file

uli*_*tko 5

你可能想使用这个技巧:

{ anycommand } | su -c 'tee file' user
Run Code Online (Sandbox Code Playgroud)

tee(1) 是 POSIX 实用程序,因此您可以依赖它的可用性。


或者,使用sudo

{ anycommand } | sudo -u user 'tee file'
Run Code Online (Sandbox Code Playgroud)


Kow*_*owh 5

使用子shell: (su -c 'psql -U postgres -c "<command>"' postgres) > file

在子 shell 中,您可以删除完成工作的权限,但输出将重定向到您的原始 shell,该 shell 仍然具有您的原始权限。