如何执行一组命令在Bash的另一个用户? [英] How to execute a group of commands as another user in Bash?

查看:149
本文介绍了如何执行一组命令在Bash的另一个用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有已经<一个href=\"http://stackoverflow.com/questions/10220019/how-to-write-a-shell-script-that-runs-some-commands-as-superuser-and-some-comman\">some 在这里问关于运行命令,其他用户存在的问题。然而,问题和答案注重的一个命令的而不是长期组命令。

There are already some existing questions asked here about running commands as another user. However, the question and answers focus on a single command instead of a long group of commands.

例如,请考虑下面的脚本:

For example, consider the following script:

#!/bin/bash
set -e

root_command -p param1  # run as root

# these commands must be run as another user
command1 -p 'parameter with "quotes" inline'
command2 -p 'parameter with "quotes" inline'
command3 -p 'parameter with "quotes" inline'

有几个重要的点,这里需要注意的:

There are a couple of important points to note here:


  • 最后的三个命令必须与使用须藤另一个用户运行。在这个例子中,有三个命令,但假设还有更多...

  • The final three commands must be run as another user using su or sudo. In the example there were three commands, but suppose that there were many more...

自行使用单引号和双引号,命令

The commands themselves make use of single and double quotes.

以上$ P $第二点pvents使用以下语法:

The second point above prevents the use of the following syntax:

su somebody -c "command"

...因为命令本身包含引号。

...since the commands themselves contain quotes.

什么是正确的方法群的命令,并在另一个用户帐户运行它们?

What is the proper way to "group" the commands and run them under another user account?

推荐答案

试试这个:

su somebody <<'EOF'
command1 -p 'parameter with "quotes" inline'
command2 -p 'parameter with "quotes" inline'
command3 -p 'parameter with "quotes" inline'
EOF

&LT;&LT; 引入的这里-DOC 的。下一个标记是分隔符,一切达与分隔符开始被送入作为标准输入命令行。把分隔符的单引号prevents此处-doc的内变量替换。

<< introduces a here-doc. The next token is the delimiter, and everything up to a line beginning with the delimiter is fed as standard input to the command. Putting the delimiter in single quotes prevents variable substitution within the here-doc.

这篇关于如何执行一组命令在Bash的另一个用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆