The command fails due to the permissions on the file redirected to. The redirection happens even before the sudo
command is invoked.
You will have to make sure that it's root that actually openes the file for writing.
The simplest way of doing that:
echo 'clock_hctosys="YES"' | sudo tee -a /etc/conf.d/hwclock >/dev/null
The echo
may be run as you ordinary user as it just produces a text string. The tee
utility will have to run as root though, and tee -a
will append data. We redirect the output to /dev/null
because tee
, by default, will duplicate its input data to its standard output in addition to writing to the indicated files.
With bash
or any shell that understands "here-strings":
sudo tee -a /etc/conf.d/hwclock >/dev/null <<<'clock_hctosys="YES"'
This is identical in effect to the above. Only the way we produce the string is changed.
Another, slightly roundabout way of doing it:
sudo sh -c 'echo clock_hctosys=\"YES\" >>/etc/conf.d/hwclock'
Here, the redirection happens within a sh -c
child shell running as root.
Or, giving the line to append as an argument to the sh -c
shell running as root:
sudo sh -c 'printf "%s\n" "$1" >>/etc/conf.d/hwclock' sh 'clock_hctosys="YES"'
... which could be generalized into something that adds all arguments as lines to the file:
set -- 'line 1' 'line 2' 'line 3'
sudo sh -c 'printf "%s\n" "$@" >>/etc/conf.d/hwclock' sh "$@"
tee
commands runs as root, not the main command which could be complex and prone to misbehaviour. (not the case ofecho
) – pabouk - Ukraine stay strong Feb 14 '15 at 11:27echo 'clock_hctosys="YES"' | sudo tee -a /etc/conf.d/hwclock >/dev/null
also does the job for something more complicated thanecho
(when we need the command output) without invoking this command under root – avtomaton Dec 02 '20 at 10:09