2

For example

echo Something >> SomeFile

I want this append to work only if SomeFile exists already.

Right now I am using the following:

if [ -e SomeFile ]; then 
    echo Something >> SomeFile
fi; 

But there should be a race condition here. During the if condition evaluation SomeFile may exist. A context switch happens between the if condition and the append. Some other application executes that removes SomeFile. In that case the append would create SomeFile.

I need to solution to work for both bsd sed and gnu sed.


It is pretty simple to do this in python with os.open and O_APPEND

$ rm SomeFile
$ python -c "import os; print(os.open(\"SomeFile\",os.O_APPEND))"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
OSError: [Errno 2] No such file or directory: 'SomeFile'
$ touch SomeFile
$ python -c "import os; print(os.open(\"SomeFile\",os.O_APPEND))"
3
  • I do not think I can achieve this with >> (output-redirection). According to this >> operation opens files with O_CREAT. – Hakan Baba Nov 19 '17 at 6:25
1

I think this should accomplish what you want:

sed -i '' -e '$a\
Something\
' SomeFile

I did this with mac osx/bsd sed so you may be able to remove the -i '' part. This will fail if SomeFile does not exist however a caveat to this is it will also fail if the file exists and is 0 bytes, hopefully that isn't a deal breaker for you.

  • I have not used sed much except for simple replace s/../../g. So sorry for uneducated questions. For gnu-sed I needed to remove the '' but not the -i. But in that case the gnu-sed appends one more extra line after Something Do you need the final new line in the sed script? I think I can work around the 0 bytes problem. I can make the file contain a new line at the start instead of being empty. Why is this command a NOOP for empty files? Is it because sed is line based and skips processing if it cannot find any lines ? – Hakan Baba Nov 19 '17 at 6:17
  • My issue with this solution is portability. I need the solution to work in BSD and in Linux. I will update the question accordingly. It should not be too difficult to modify the parameters and the sed script to generate the same output for bsd and gnu seds. – Hakan Baba Nov 19 '17 at 6:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.