Home > front end >  Output redirection does not work correctly when script contains sed
Output redirection does not work correctly when script contains sed

Time:11-09

I have following file structure:

-script.sh
-directory (empty directory)

script.sh code:

#!/bin/bash
echo "Start"

find . -type f | xargs sed -r -i '' "s/a/b/g"

echo 'After find/sed'

I run ../script.sh | tee out.log from directory and get following results:

  • terminal output
Start
After find/sed
  • cat out.log
Stbrt

But I expected to see the same result for cat out.log as for terminal output.

  1. Why terminal output and out.log differ?
  2. How can script affect content of out.log? Isn't it created after script is finished? (we see it is affected: Start -> Stbrt)

CodePudding user response:

Why terminal output and out.log differ?

sed -i creates a temporary file and then moves the temporary file into file to be modified.

tee opens the file and writes to the file descriptor.

The file out.log opened by tee is no longer there. sed sees the first line of the file, modifies it, and moves the new file to out.log. tee continues writing the second line to the file that is no longer reachable through the directory inode. You are seeing the file modified by sed.

How can script affect content of out.log if it should be created after script is finished?

Script finishing execution and creation of out.log file are unsequenced. They can happen in any order, which depends on which process get's CPU and kernel time and on I/O time. In your case, tee creates the file first and writes there the first line of output, before sed can execute, so sed sees the file and replaces it.

  • Related