When I do foo > bar.txt, bar.txt will be created no matter if foo succeeded or not. How can I create bar.txt only if foo succeeded?
Asked
Active
Viewed 679 times
1
maddingl
- 197
- 4
- 20
-
1Redirect to a temporary file and then move it to the real file if the command succeeds (else delete it). Or just plain delete the file if the command failed? – Some programmer dude Apr 23 '20 at 08:16
-
use `&&` https://stackoverflow.com/questions/4510640/what-is-the-purpose-of-in-a-shell-command – Chris Apr 23 '20 at 08:16
1 Answers
2
foo > bar.txt || rm bar.txt should work and is short and concise.
maddingl
- 197
- 4
- 20
-
3Beautiful solution, but if the file `bar.txt` already existed, you will lose its previous version without having a new one. In most cases, this is not a problem. – Pierre François Apr 23 '20 at 08:36