在 bash 中生成脚本并将其保存到需要 sudo 的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4412029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate script in bash and save it to location requiring sudo
提问by D W
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
在 bash 中,我可以创建一个带有 here-doc 的脚本,就像这个站点一样: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
If my $OUTFILEis a directory requiring sudoprivileges where do I put the sudocommand or what else can I do to make it work?
如果我$OUTFILE是一个需要sudo特权的目录,我应该把sudo命令放在哪里,或者我还能做些什么来使它工作?
采纳答案by Laurence Gonsalves
Just putting sudobefore catdoesn't work because >$OUTFILEattempts to open $OUTFILEin the current shell process, which is not running as root. You need the opening of that file to happen in a sudo-ed subprocess.
只是放在sudobeforecat不起作用,因为>$OUTFILE尝试$OUTFILE在当前的 shell 进程中打开,该进程不是以 root 身份运行的。您需要在sudo-ed 子进程中打开该文件。
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
This starts a sub-shell under sudo, and opens $OUTFILEfrom that more privileged subprocess, and runs cat(as yet another privileged subprocess). Meanwhile, the (less privileged) parent process pipes the here-document to the sudosubprocess.
这将在 下启动一个子 shell sudo,并$OUTFILE从该更高特权的子进程打开,并运行cat(作为另一个特权子进程)。同时,(特权较低的)父进程通过管道将 here-document 传递给sudo子进程。
回答by Paused until further notice.
This is how I would do it:
这就是我将如何做到的:
sudo tee "$OUTFILE" > /dev/null <<'EOF'
foo
bar
EOF
回答by Wolfgang Fahl
Non of the answers expanded environment variables. My workaround is a tmp file and a sudo mv.
没有一个答案扩展了环境变量。我的解决方法是一个 tmp 文件和一个 sudo mv。
l_log=/var/log/server/server.log
l_logrotateconf=/etc/logrotate.d/server
tmp=/tmp/$$.eof
cat << EOF > $tmp
$l_log {
rotate 12
monthly
compress
missingok
notifempty
}
EOF
sudo mv $tmp $logrotateconf

