Interesting bash behavior

Why does this command (creating an empty folder, changing it, touching a file, calling ls, and then cating) display two files?

root@ubuntu:~# mkdir a ; cd a ; touch b ; ls > c ; cat c
b
c

I believe that I only need a "b".

+4
source share
4 answers

When you redirect the output lsto a file c, this is a chicken and egg problem:

If cit was not created in advance, this meant that the shell would need to save the output in a buffer and (at the end) write this buffer to a file.

Since in many cases this is not the best approach (due to memory management, failure management for commands that are interrupted before completion, etc.), the file is created in advance.

, , .

+5

ls > c

c ls. touch b ( b - ). ,

mkdir t ; cd t ; ls > a ; cat a

a (, > a ls exec ).

+3

( ), ls .

, ls .

+1

, ls c, , .

( ):

  • ( ).
  • ( , , ).
  • , .
  • , .

3, , , , .

, (ls ), (c ) , .

, c.

0

Source: https://habr.com/ru/post/1612154/


All Articles