help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Quick prepend to file using echo


From: John Kearney
Subject: Re: [Help-bash] Quick prepend to file using echo
Date: Thu, 17 May 2012 00:53:18 -0700

Depending on the size of the file you could try.

Buffer="prepended data"
Buffer+="$(<file)"

Echo "${Buffer}" >file


Von: Eric Blake
Gesendet: 16.05.2012 19:24
An: address@hidden
Betreff: Re: [Help-bash] Quick prepend to file using echo
On 05/16/2012 05:16 PM, Chris Jones wrote:
> Using ‘echo’, it's easy to append to a file:
>
> --------------------------------------------------------------------------------
> $ echo "// vim: set tw=80 syntax=sh:" >> ~/.bashrc
> --------------------------------------------------------------------------------
>
> But how do you do it the other way around..? Prepend to a file so-to-speak..?
>
> I saw a couple of threads in stackoverflow.com with complicated one-liners and
> everybody appeared to conclude that you need a temp file anyway..
>
> So how about:
>
> --------------------------------------------------------------------------------
> $ echo -e "$(echo -e "// vim: set tw=80 syntax=sh: ";cat ~/.bashrc)" > 
> ~/.bashrc
> --------------------------------------------------------------------------------

'echo -e' is non-portable; you should really be using printf instead.

This command is an epic failure.  You are causing a race between the
shell truncating ~/.bashrc and the $() command substitution that spawns
cat to read the contents of ~/.bashrc.  You MUST use a temporary file
for safety.

>
> - how does it work..? Namely why isn't the file overwritten..?

It _doesn't_ work.  It's still quite racy, where you are relying on the
process executing the $() to fire, _and_ getting far enough along to
start the cat process, _all_ before the outermost shell truncates ~/.bashrc.

> - barring a power failure while running.. could this cause data loss..?

Most certainly it will cause data loss.

> - is there a portable way to do it with printf..?

Only by using a temporary file.

THAT SAID,

if you use GNU sed, you can use the -i option for in-place editing to
insert a line before the contents, and let sed take care of the creation
of a temporary file under the hood (yes, a temporary file is _still_
involved, but at least you don't have to explicitly name it).

-- 
Eric Blake   address@hidden    +1-919-301-3266
Libvirt virtualization library http://libvirt.org



reply via email to

[Prev in Thread] Current Thread [Next in Thread]