Skip to content
koalaman edited this page Sep 26, 2017 · 9 revisions

sudo doesn't affect redirects. Use ..| sudo tee file

Problematic code:

sudo echo 'export FOO=bar' >> /etc/profile

Correct code:

echo 'export FOO=bar' | sudo tee -a /etc/profile > /dev/null

Rationale:

Redirections are performed by the current shell before sudo is started. This means that it will use the current shell's user and permissions to open and write to the file.

tee is a simple command that opens and writes to files without help from the shell, which means that it will use the permissions that sudo grants it.

There is nothing special about tee. It's just the simplest command that can both truncate and append to files without help from the shell. Here are equivalent alternatives:

Truncating:

echo 'data' | sudo dd of=file
echo 'data' | sudo sed 'w file'

Appending:

echo 'data' | sudo awk '{ print $0 >> "file" }'
echo 'data' | sudo sh -c 'cat >> file'

Exceptions

If you want to run a command as root but redirect as the normal user, you can ignore this message.

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature above to find a specific one, or see Checks.

Clone this wiki locally