Long shell commands with sudo sh -c: quoting
Two patterns to run a long shell command with pipes and quotes as root, and the escaping pitfalls to avoid.
Quoting becomes hard when a command with pipes, redirections and quotes must run as root. Two patterns are used.
Pattern 1: sudo sh -c with single quotes
sudo sh -c 'echo clock_hctosys=\"YES\" >> /etc/conf.d/hwclock'
Pattern 2: write the command as a $'...' string and pipe it into sudo sh
echo $'lsof -P -i tcp | awk \'{print $2,$4}\' | tr -d \'u\' | sort -u | while read pid fd; do stat --printf "%z %N\n" /proc/$pid/fd/$fd ; done | sort -r' | sudo sh
The $'...' form escapes the single quotes and does not expand $ variables in the calling shell, so $2, $4, $pid and $fd are expanded by the root shell that runs the text.
Notes
- Inside single quotes,
\"is passed on as a literal backslash followed by a quote. Write'echo clock_hctosys="YES" >> /etc/conf.d/hwclock'if plain double quotes are wanted. - The source also had a
sudo sh -c "..."variant with unescaped$2and$4and nested double quotes. It is not reproduced: inside double quotes the calling shell expands$2and$4beforesudoruns. Use pattern 2 for such commands.