From 08bd914ed5ef3e274338864b8254b15520759366 Mon Sep 17 00:00:00 2001 From: koalaman Date: Mon, 27 Jan 2014 23:18:56 -0800 Subject: [PATCH] Created SC2094 (markdown) --- SC2094.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 SC2094.md diff --git a/SC2094.md b/SC2094.md new file mode 100644 index 0000000..c9cf5d5 --- /dev/null +++ b/SC2094.md @@ -0,0 +1,24 @@ +# SC2094 Make sure not to read and write the same file in the same pipeline. + +### Problematic code: + + grep foo file.txt | sed -e 's/foo/bar/g' > file.txt + +### Correct code: + + grep foo file.txt | sed -e 's/foo/bar/g' > tmpfile && mv tmpfile file.txt + +### Rationale: + +Each step in a pipeline runs in parallel. + +In this case, `grep foo file.txt` will immediately try to read `file.txt` while `sed .. > file.txt` will immediately try to truncate it. + +This is a race condition, and results in the file being partially or (far more likely) entirely truncated. + +### Contraindications + +You can ignore this error if: + +* The file is a device or named pipe. These files don't truncate in the same way. +* The command mentions the filename but doesn't read/write it, such as `echo log.txt > log.txt`. \ No newline at end of file