在bash中生成脚本并将其保存到需要sudo的位置 [英] Generate script in bash and save it to location requiring sudo

查看:57
本文介绍了在bash中生成脚本并将其保存到需要sudo的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash中,我可以使用一个here-doc创建脚本,如下所示: http://tldp.org/LDP/abs/html/abs-guide.html#GENERATESCRIPT

In bash I can create a script with a here-doc like so as per this site: http://tldp.org/LDP/abs/html/abs-guide.html#GENERATESCRIPT

(
cat <<'EOF'
#!/bin/bash
#? [ ] / \ = + < > : ; " , * | 
#/ ? < > \ : * | "
#Filename="z:"${$winFn//\//\\}
echo "This is a generated shell script."
App='eval wine "C:\Program Files\foxit\Foxit Reader.exe" "'$winFn'"'
$App
EOF
) > $OUTFILE

如果我的 $ OUTFILE 是一个需要 sudo 特权的目录,我应该在其中放置 sudo 命令,或者可以做些什么呢?工作吗?

If my $OUTFILE is a directory requiring sudo privileges where do I put the sudo command or what else can I do to make it work?

推荐答案

仅将 sudo 放在 cat 之前是行不通的,因为> $ OUTFILE 尝试在当前未以root用户身份运行的shell进程中打开 $ OUTFILE .您需要打开该文件才能在 sudo 版本的子进程中进行.

Just putting sudo before cat doesn't work because >$OUTFILE attempts to open $OUTFILE in the current shell process, which is not running as root. You need the opening of that file to happen in a sudo-ed subprocess.

这是完成此任务的一种方法:

Here's one way to accomplish this:

sudo bash -c "cat >$OUTFILE" <<'EOF'
#!/bin/bash
#? [ ] / \ = + < > : ; " , * | 
#/ ? < > \ : * | "
#Filename="z:"${$winFn//\//\\}
echo "This is a generated shell script."
App='eval wine "C:\Program Files\foxit\Foxit Reader.exe" "'$winFn'"'
$App
EOF

这将在 sudo 下启动一个子shell,并从该特权更高的子进程中打开 $ OUTFILE ,并运行 cat (还有另一个特权子进程).同时,(特权较少的)父进程将此处文档传递给 sudo 子进程.

This starts a sub-shell under sudo, and opens $OUTFILE from that more privileged subprocess, and runs cat (as yet another privileged subprocess). Meanwhile, the (less privileged) parent process pipes the here-document to the sudo subprocess.

这篇关于在bash中生成脚本并将其保存到需要sudo的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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