[sf-lug] sudo

Daniel Gimpelevich daniel at gimpelevich.san-francisco.ca.us
Wed Nov 8 19:33:58 PST 2017


On Wed, 2017-11-08 at 18:30 -0800, Alex Kleider wrote:
> I am working with a headless Raspberry Pi and would like to be able
> to add a line to a file owned by root but would like to do this from
> within a bash script that itself is not run with root privileges.[1]
> 
> Here is what I have come up with so far:
> 
> 
> #!/bin/bash
> # File: t.sh
> 
> export ap_ip=10.10.10.10
> 
> sudo sh -c 'echo "$ap_ip  library library.lan rachel rachel.lan" >> 
> /etc/hosts'
> 
> 
> 
> This seems to work except for the fact that the variable ap_ip
> does not get inserted, only the other part of the line.
> I think it's because the quoting has not allowed the variable to
> be passed.
> 
> Can anyone advise how this should be done?
> Thanks in advance.

Two options:
1) sudo sh -c "echo \"$ap_ip  library library.lan rachel rachel.lan\"
>> /etc/hosts"
2) echo "$ap_ip  library library.lan rachel rachel.lan" | sudo tee
-a /etc/hosts > /dev/null

> [1] It so happens that the Raspberry Pi does not ask for a password
> when an sudo command is issued (not sure how that is- not seen it
> on any other Linux system.)

Obviously, the NOPASSWD option is set for that user/command combo. See:
man 5 sudoers




More information about the sf-lug mailing list