32

在 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

如果我$OUTFILE是一个需要sudo权限的目录,我应该把sudo命令放在哪里,或者我还能做些什么来让它工作?

4

3 回答 3

71

我会这样做:

sudo tee "$OUTFILE" > /dev/null <<'EOF'
foo
bar
EOF
于 2010-12-11T01:58:48.983 回答
27

只是放sudo之前cat不起作用,因为>$OUTFILE试图$OUTFILE在当前的 shell 进程中打开,它不是以 root 身份运行的。您需要在sudo-ed 子进程中打开该文件。

这是实现此目的的一种方法:

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

这会在 下启动一个子 shell sudo,并从该特权更高的子进程打开$OUTFILE,然后运行cat(作为另一个特权子进程)。同时,(较少特权的)父进程通过管道将 here-document 传递给sudo子进程。

于 2010-12-10T18:33:44.030 回答
0

没有答案扩展了环境变量。我的解决方法是一个 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
于 2019-12-24T04:32:28.770 回答