From 9250f97d58d407909282372db190e07b7b756a52 Mon Sep 17 00:00:00 2001 From: koalaman Date: Thu, 11 Sep 2014 11:13:46 -0700 Subject: [PATCH] Updated SC2024 (markdown) --- SC2024.md | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/SC2024.md b/SC2024.md index 8a25a32..e9b5831 100644 --- a/SC2024.md +++ b/SC2024.md @@ -1,9 +1,32 @@ -# SC2024 sudo doesn't affect redirects. Use ..| sudo tee file +## sudo doesn't affect redirects. Use ..| sudo tee file -## Problematic Code: +### Problematic code: - sudo echo 'export FOO=bar' > /etc/profile + sudo echo 'export FOO=bar' >> /etc/profile -## Correct Code: +### Correct code: - echo 'export FOO=bar' | sudo tee /etc/profile > /dev/null + 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' + + +### Contraindications + +If you want to run a command as root but redirect as the normal user, you can ignore this message. \ No newline at end of file