简体   繁体   中英

bash script: sudo no interactive echo redirection to a file

in a bash script I'm trying to redirect a text printed with echo with sudo non interactive to a file. But I'm not clear about how to do it.

I tried with this code:

echo $sudopass| sudo -S echo "user ALL=(ALL) NOPASSWD:ALL" >     /etc/sudoers.d/ansible

Output redirection is not affected by elevated sudo permissions. The part that you sudo is the echo , not the redirection of that command's output.

That will still happen with your current user's permission.

So you need a way to append a line to a file that does not involve output redirection.


Note: Earlier version of this answer showcasing sed removed as sed balks if the target file is empty or non-existing. As I wanted to keep the gist of the answer intact -- "how to avoid output redirection" -- I added instructions on how to use vi for the same purpose.


Every POSIX-compliant system needs to have the vi / ex editor. (On contemporary Linux machines usually a link starting Vim in compatiblity mode.) You can "remote-control" ex / vi / Vim through the command line:

vi -es -c "normal! G" -c "normal! ouser ALL=(ALL) NOPASSWD:ALL" -c "x" /etc/sudoers.d/ansible

(This is without the sudo part for clarity.)

Explanation:

  • -e starts vi in "ex mode". (Equivalent to calling ex .)
  • -s means "silent" -- no prompts, no messages.
  • -c passes a command to the editor to be executed once the first file has been read.
  • "normal! G" first puts the editor in "normal mode" -- that is what you would find yourself in if you started vi interactively; ex is in "command mode" by default (as if you entered : in vi). The G moves the cursor to the last line.
  • "normal! o..." again activates normal mode, adds a line after the current line, and activates "insert mode". The rest of the string is entered verbatim.
  • "x" saves the file and exits the editor.

The command line including the sudo part:

echo $sudopass | sudo -S vi -es -c "normal! G" -c "normal! ouser ALL=(ALL) NOPASSWD:ALL" -c "x" /etc/sudoers.d/ansible

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM