SC2024 – ShellCheck Wiki

See this page on GitHub


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

or "Use ..| sudo tee -a file" instead of >> to append.

or "Use sudo cat file | .." instead of < to read.

Problematic code:

# Write to a file
sudo echo 3 > /proc/sys/vm/drop_caches

# Append to a file
sudo echo 'export FOO=bar' >> /etc/profile

# Read from a file
sudo wc -l < /etc/shadow

Correct code:

# Write to a file
echo 3 | sudo tee /proc/sys/vm/drop_caches > /dev/null

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

# Read from a file
sudo cat /etc/shadow | wc -l


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 read from or write to the file.

The substitutions work by having a command open the file for reading or writing, instead of relying on the current shell. Since the command is run with elevated privileges, it will have access to files that the current user does not.

Note: 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:


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


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


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

ShellCheck is a static analysis tool for shell scripts. This page is part of its documentation.