Re: shell script replacing original file

Re: shell script replacing original file

am 31.03.2008 14:01:12 von Janis Papanagnou

On 28 Mrz., 19:12, "Chris F.A. Johnson" wrote:
> On 2008-03-28, Maxwell Lol wrote:
>
> > "Ming Ching TIew" writes:
>
> >> I want to know if it is 100 % safe to do this :-
>
> >> =A0 =A0$ cat myfile | sed -e '...........' =A0> myfile
>
> > (p.s. No need for cat.)
>
> =A0 =A0In this case, cat is needed so that myfile is opened before the
> =A0 =A0redirection truncates it. Even so, I wouldn't trust it.

A sequence of identical invocations... (note the file size)

$ ksh -c 'ls >myfile ; cat myfile | sed -e "s/a/A/g" > myfile'
$ ls -l myfile
-rwxrwxrwa 1 ... ... 435 Mar 31 13:49 myfile
$ ksh -c 'ls >myfile ; cat myfile | sed -e "s/a/A/g" > myfile'
$ ls -l myfile
-rwxrwxrwa 1 ... ... 0 Mar 31 13:49 myfile
$ ksh -c 'ls >myfile ; cat myfile | sed -e "s/a/A/g" > myfile'
$ ls -l myfile
-rwxrwxrwa 1 ... ... 0 Mar 31 13:49 myfile
$ ksh -c 'ls >myfile ; cat myfile | sed -e "s/a/A/g" > myfile'
$ ls -l myfile
-rwxrwxrwa 1 ... ... 435 Mar 31 13:49 myfile

(And I get the same effect if replacing ksh with bash.)

So I'd say, indeed, "No need for cat"; programming that way seems
to be just a bug - assuming one doesn't want to program a random
event generator by that programming pattern.

Janis

>
> > Well, if you want to be 100% safe, perhaps something like this is better=

>
> > =A0 =A0 =A0 =A0 sed -e '...........' =A0 myfile.new
> > =A0 =A0 =A0 =A0 mv myfile myfile.old && mv myfile.new myfile && /bin/rm =
myfile.old
>
> > If it's a large file, and the disk fills up, it won't delete the
> > original file. (untested)
>
> --
> =A0 =A0Chris F.A. Johnson, author =A0 =A0 =A0 hell/>
> =A0 =A0Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)=

> =A0  ===== My code in this post, if any, assumes the POSIX loc=
ale
> =A0  ===== and is released under the GNU General Public Licenc=
e