Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Interesting bash behaviour

Tags:

bash

shell

sh

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

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

I believe that I should only get "b".

like image 249
Николай Кондратюк Avatar asked Jan 07 '23 08:01

Николай Кондратюк


1 Answers

When you redirect the output of ls to the file c, it's a chicken and egg problem:

If c would not be created upfront, that would mean the shell would need to store the output in a buffer and (in the end) write that buffer to the file.

Since this is not the best approach in many cases (because of memory management, management of failure for commands that get interrupted before completion, etc.), the file gets created upfront.

Thus, the standard output for the command can be replaced with the newly created file and the command output can be streamed to that file.

like image 145
Costi Ciudatu Avatar answered Jan 18 '23 06:01

Costi Ciudatu