2

This might look like a very simple question but I haven't been able to come up with a proper explanation so far. Say I use tr to transform some random text(it can be any program) and want to output the result into the original file.

a@MacBook-Pro:~/Downloads$ cat test_file 
this is a sample text
a@MacBook-Pro:~/Downloads$ tr 't' 'T' <test_file >test_file 
a@MacBook-Pro:~/Downloads$ cat test_file #prints nothing

Is there any specific rule/thing that tells us we can't be redirecting both input and output to the same file at the same time? I obviously know that I could have redirected the output into the new file and then copied the result but I am very curious about this behavior.

P.S I have been using a Macbook, but this shouldn't matter in this case

1 Answer 1

4
>test_file

Truncates the file. then you read a blank file and write nothing back to it.

Use sponge if you don't want to create a new file.

tr 't' 'T' <test_file | sponge test_file 

There is also a nice answer at superuser addressing this question: Why does redirecting the output of a file to itself produce a blank file?

PS: I Supposed you are running Ubuntu on a mac.

3
  • 1
    Thanks for the answer and the link. I just have one more question. Does the redirection order matter in this case? Or it is just how bash operates? (it always opens stdout before stdin?)
    – Alex.Kh
    Commented Nov 5, 2020 at 23:01
  • 1
    Yes, the order matters, but the shell has to setup the file IO before it launches the command. Commented Nov 6, 2020 at 0:35
  • Remember, if the output from the command is empty will empty the file.
    – user986805
    Commented Nov 7, 2020 at 19:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .