Redirecting and then moving target file

Viewed 164

I tested the following on AIX and it works.

logfile=log.txt
echo "Hello" > "$logfile"
exec 1>>"$logfile"
mv "$logfile" "${logfile}_new"
echo "World"

After this script ran the file log.txt_new will contain:

Hello
World

I was not expecting it to work because I renamed the file to where stdout was being redirected. Why does it work?

It also works if I mv/rename the directory that contains the log file.

Answer: https://unix.stackexchange.com/questions/7707/how-do-open-files-behave-on-linux-systems

1 Answers

The confusion comes from the command mv.

In this case, mv does not really move the file, but just give it a new name.

The content of the file stays unchanged, and it's still the destination of the standard output of your current shell.

That's why the echo command still outputs into the original file.

Related