[英]Generate script in bash and save it to location requiring sudo
在 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
命令放在哪里,或者我還能做些什么來使它工作?
這就是我將如何做到的:
sudo tee "$OUTFILE" > /dev/null <<'EOF'
foo
bar
EOF
將sudo
放在cat
之前是行不通的,因為>$OUTFILE
嘗試在當前 shell 進程中打開$OUTFILE
,該進程不是以 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
這將在sudo
下啟動一個子 shell,並從該更高特權的子$OUTFILE
打開$OUTFILE
,並運行cat
(作為另一個特權子進程)。 同時,(特權較低的)父進程通過管道將 here-document 傳遞給sudo
子進程。
沒有一個答案擴展了環境變量。 我的解決方法是一個 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.