Here's how to reproduce it:
echo 'the original file' > orig
ln -s orig symb # now symb is symlinked to orig
cat symb > orig # this makes orig an EMPTY FILE, but why?
orig
becomes an empty file after the third command, but why?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communitySymlinks are evaluated as you attempt to open a file. Under "normal" circumstances the result of opening a symbolic link is to open the file it references. So:
ln -s original_file my_symlink
cat my_symlink > original_file
Is very similar to:
cat original_file > original_file
Why does it destroy the content?
In any shell command > some_file
will first open and truncate (zero) some_file
and then execute command
, writing the result to some_file
.
So if you cat x > x
then the shell will open and truncate x
, then cat x
will open and read the truncated file writing all of it's zero bytes.
cat orig >orig
. Are you thinking you're doing something different?cat
command performs the redirection. If this is what you think, you are wrong. It is the shell. Before executingcat
, the shell processes> orig
. This means that it creates an emptyorig
if it doesn't exist, or it resetsorig
to a size of 0 if it exists. After that,cat
is called, its stdout connected toorig
.