Generate script in bash and save it to location requiring sudo

北城以北 提交于 2021-02-05 20:23:51

问题


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

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?


回答1:


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

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.




回答2:


This is how I would do it:

sudo tee "$OUTFILE" > /dev/null <<'EOF'
foo
bar
EOF



回答3:


Non of the answers expanded environment variables. My workaround is a tmp file and a 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


来源:https://stackoverflow.com/questions/4412029/generate-script-in-bash-and-save-it-to-location-requiring-sudo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!