LLI Wiki — My Digital Knowledge Base

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

Mastodon LLIMastodon SocialFosstodon