Generate script in bash and save it to location requiring 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'"'$AppEOF
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.
Non of the answers expanded environment variables. My workaround is a tmp file and a sudo mv.
l_log=/var/log/server/server.logl_logrotateconf=/etc/logrotate.d/servertmp=/tmp/$$.eofcat << EOF > $tmp$l_log { rotate 12 monthly compress missingok notifempty}EOFsudo mv $tmp $logrotateconf