You are not logged in.
Hi,
I'm doing a CS course at University and in one of my modules I have to do some shell scripting. For one of the first assignments I have to write a shell script that swaps the contents of two files by moving one to a new temporary location and then swapping them over. I completed this task without any problems, but I had an interesting thought about manipulating files in shell scripts. It seems that it is very common to test to see if a file exists with [ -e filename ] and then proceed on the information gained. However, as every good programmer knows this method is possibly susceptible to at best an annoying bug and at worst a symlink attack, because the operation is not atomic and the file could be created, destroyed, changed to a symlink etc. in between the test and the operation based on that test.
Now I know this is probably overkill for my lame university assignment, but I thought it would be fun to try and find a safe way to do this
In my case, since I am moving to a temporary file I thought it would be good to use the -n option on cp or mv to avoid clobbering the target. Unfortunately, cp/mv still return 0 if the transaction fails due to exisiting file so it takes a bit more work. If you use the -v argument then the utility will print one line of output per file copied/moved, so one solution would be
cp -nv source dest | wc | awk '{print $1}'
which would be 0 if the destination already exists or 1 if one file copied successfully.
Obviously that's a bit long-winded though. Has anyone got a cooler way to do it?
Offline
sure you can have race conditions, that's why you should also check if the copy/move/.. completed successfully.
As for the symlink/move different file/.. "attack". this is just a matter of security (eg permissions/ACL's). if you don't want people to mess/put/move/... files you should just use appropriate acl's.
< Daenyth> and he works prolifically
4 8 15 16 23 42
Offline
-n is non-standard. I don't have it.
If you use an alternative like yes n | cp -i, that script won't work.
Offline
Hmmm I've confused myself now, time to do some reading!
Last edited by Bralkein (2009-02-27 15:10:37)
Offline